Singleton
Why build a Singleton?
Singleton pattern ensures only one instance of a class is ever created and it provides a global access to the instance.
How to build?
Singleton pattern ensures only one instance of a class is ever created and it provides a global access to the instance.
How to build?
Unlike Java which uses identifiers like private/public identifiers, Darts precede method with a dash "_" to make class/instance private.
A constructor is used to invoke the static private instance _singleton . Note that you do not need the “new” keyword to invoke the constructor. You can also make the instance public, by removing the dash in front of its name.
1. Building a Singleton:
class Singleton {
static final Singleton _singleton = new Singleton._internal();
factory Singleton() {
return _singleton;
}
Singleton._internal();
}
2.Static field with getter
class SingletonTwo {
SingletonTwo._privateConstructor();
static final SingletonTwo _instance = SingletonTwo._privateConstructor();
static SingletonTwo get instance { return _instance;}
}
3. Static
class SingletonThree {
SingletonThree._privateConstructor();
static final SingletonThree instance = SingletonThree._privateConstructor();
}
Instantiate
SingletonOne one = SingletonOne();
SingletonTwo two = SingletonTwo.instance;
SingletonThree three = SingletonThree.instance;
Comments
Post a Comment