Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you build a Singleton in Dart?

Tags:

singleton

dart

The singleton pattern ensures only one instance of a class is ever created. How do I build this in Dart?

like image 617
Seth Ladd Avatar asked Sep 29 '12 02:09

Seth Ladd


2 Answers

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 } 
like image 93
Seth Ladd Avatar answered Sep 30 '22 03:09

Seth Ladd


Here is a comparison of several different ways to create a singleton in Dart.

1. Factory constructor

class SingletonOne {    SingletonOne._privateConstructor();    static final SingletonOne _instance = SingletonOne._privateConstructor();    factory SingletonOne() {     return _instance;   }  } 

2. Static field with getter

class SingletonTwo {    SingletonTwo._privateConstructor();    static final SingletonTwo _instance = SingletonTwo._privateConstructor();    static SingletonTwo get instance => _instance;    } 

3. Static field

class SingletonThree {    SingletonThree._privateConstructor();    static final SingletonThree instance = SingletonThree._privateConstructor();    } 

How to instantiate

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.

like image 45
Suragch Avatar answered Sep 30 '22 03:09

Suragch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!