Dart: Singleton
Singleton is a creational design pattern that lets you ensure that a class has only one instance, while providing a global access point to this instance.
Let’s see how to implement a singleton in Dart. First, we will create a simple class.
class Singleton {}
We need to ensure that our class will have just one instance.
Let’s create a private constructor.
class Singleton {
Singleton._();
}
With a private constructor we can’t instantiate our class outside of it.
Now, we will to create a final static variable to store our instance.
class Singleton {
Singleton._();
static final Singleton _instance = Singleton._();
}
This variable will be initialized with our private constructor.
Finally, we will create a factory constructor to return our instance.
class Singleton {
Singleton._();
static final Singleton _instance = Singleton._();
factory Singleton() {
return _instance;
}
}
factory constructor
: is a constructor that doesn’t always create a new instance of its class. It’s used to control the way in which an object is created.
Ok, our singleton seems ready to use. Let’s test it.
void main() {
//check objects
var obj1 = Singleton();
var obj2 = Singleton();
print(identical(obj1, obj2)); //true
//check hashcode
var hashcode1 = obj1.hashCode;
var hashcode2 = obj2.hashCode;
print(hashcode1 == hashcode2); //true
}
object.hashCode
: is a hash code representing the object. It’s not guaranteed to be unique, but it’s guaranteed to be the same for equal objects.