The singleton pattern ensures only one instance of a class is ever created. How do I build this in Dart?
Thanks to Dart's factory constructors, it's easy to build a singleton:
class Singleton { static final Singleton _singleton = Singleton._internal(); factory Singleton() { return _singleton; } Singleton._internal(); } You can construct it like this
main() { var s1 = Singleton(); var s2 = Singleton(); print(identical(s1, s2)); // true print(s1 == s2); // true }
Here is a comparison of several different ways to create a singleton in Dart.
class SingletonOne { SingletonOne._privateConstructor(); static final SingletonOne _instance = SingletonOne._privateConstructor(); factory SingletonOne() { return _instance; } } class SingletonTwo { SingletonTwo._privateConstructor(); static final SingletonTwo _instance = SingletonTwo._privateConstructor(); static SingletonTwo get instance => _instance; } class SingletonThree { SingletonThree._privateConstructor(); static final SingletonThree instance = SingletonThree._privateConstructor(); } The above singletons are instantiated like this:
SingletonOne one = SingletonOne(); SingletonTwo two = SingletonTwo.instance; SingletonThree three = SingletonThree.instance; Note:
I originally asked this as a question, but discovered that all of the methods above are valid and the choice largely depends on personal preference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With