Last active
January 30, 2020 08:40
-
-
Save AlexKenbo/23900c965f4f6618b6dba0bee7fb3d81 to your computer and use it in GitHub Desktop.
Singleton (design pattern). Что такое _приватный конструктор?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void main() { | |
Map<String,dynamic> bob = { | |
'name': 'Bob', | |
}; | |
Map<String,dynamic> bobLike = { | |
'name': 'Bob', | |
}; | |
if(bob == bobLike) { | |
print('equal'); | |
} else print('Instance bob not equal Instance bobLike'); | |
if({} == {}) { | |
print('equal'); | |
} else print('InstanceA {} not equal instanceB {}'); | |
PersonSingleton john1 = PersonSingleton('John'); | |
PersonSingleton john2 = PersonSingleton('John'); | |
if(john1 == john2) print('john1 equal john2, это один и тот же экземпляр'); | |
Person jim = Person('JIM'); | |
Person jimLike = Person('JIM'); | |
if(jim == jimLike){ | |
print('equal'); | |
} else | |
{ print('jim не равен jimLike, так как это разные экземпляры, хотя значения равные'); } | |
Singleton s1 = Singleton(); | |
Singleton s2 = Singleton(); | |
Singleton s3 = Singleton(); | |
if(s1 == s2 && s2 == s3) print('В переменных s1, s2, s3 храниться один и тот же экземпляр SingletonOne'); | |
print('\nCounter'); | |
Counter muCount1 = Counter(); | |
Counter muCount2 = Counter(); | |
muCount1.increaseCount(); | |
muCount1.increaseCount(); | |
muCount2.increaseCount(); | |
muCount2.increaseCount(); | |
print(muCount1.getCount()); | |
print(muCount2.getCount()); | |
//Три способа создания синглтона | |
SingletonOne one = SingletonOne(); | |
SingletonTwo two = SingletonTwo.instance; | |
SingletonTwo two2 = SingletonTwo(); // error The class 'SingletonTwo' doesn't a have default constructor | |
SingletonThree three = SingletonThree.instance; | |
} | |
/* | |
Что за именнованный конструктор _internal? | |
Конструкция _internal - это просто имя, часто присваиваемое конструкторам, которые являются приватными для класса. Имя не обязательно должно быть ._internal, вы можете создать любой приватный конструктор, начинающийся с подчеркивания или содержащий только подчеркивание: Class._someName(), Foo._() | |
Например, следующий код позволяет создавать новых людей только за пределами класса с помощью конструктора PersonSingleton(name), который является фабричным и в последствии вызывает приватный конструктор PersonSingleton._internal(name) | |
*/ | |
class PersonSingleton { | |
final String name; | |
static Map<String,PersonSingleton> _cache; | |
factory PersonSingleton(String name) { | |
if(_cache == null) { | |
_cache = Map<String,PersonSingleton>(); | |
} | |
if(_cache[name] == null) { | |
_cache[name] = PersonSingleton._internal(name); | |
} | |
return _cache[name]; | |
} | |
PersonSingleton._internal(this.name); | |
} | |
// А это не синглтон, так как каждый вызом Person(), создает новый экземпляр | |
class Person { | |
final String name; | |
Person(this.name); | |
} | |
// Синглтон конструктор которого вызывается без параметров (внутри могу инициализироваться какие-то переменные) | |
class Singleton { | |
Singleton._(); | |
static final Singleton _instance = Singleton._(); | |
factory Singleton(){ | |
return _instance; | |
} | |
} | |
// Пример из https://www.youtube.com/watch?v=GrYs0qDQEp0&list=PLNkWIWHIRwMGzgvuPRFkDrpAygvdKJIE4&index=2 переписанный на Dart | |
class Counter { | |
int _count; | |
static Counter _instance; | |
factory Counter() { | |
if(_instance == null) { | |
_instance = Counter._internal(); | |
_instance.setCount(0); | |
} | |
return _instance; | |
} | |
int getCount() { return _count;} | |
int increaseCount() { return _count++;} | |
void setCount(count) { _count = count; } | |
Counter._internal(); | |
} | |
//1. Create Factory constructor | |
class SingletonOne { | |
SingletonOne._privateConstructor(); | |
static final SingletonOne _instance = SingletonOne._privateConstructor(); | |
factory SingletonOne(){ | |
return _instance; | |
} | |
} | |
//2. Create Static field with getter | |
class SingletonTwo { | |
SingletonTwo._privateConstructor(); | |
static final SingletonTwo _instance = SingletonTwo._privateConstructor(); | |
static SingletonTwo get instance { return _instance;} | |
} | |
//3. Create Static field | |
class SingletonThree { | |
SingletonThree._privateConstructor(); | |
static final SingletonThree instance = SingletonThree._privateConstructor(); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment