class Singleton {
static final Singleton _instance = Singleton._internal();
factory Singleton() => _instance;
Singleton._internal();
}
// Whenever you need to get the singleton, call its factory constructor, e.g.:
// var singleton = Singleton();
//
// You'll always get the same instance.
class FileSystemManager {
static final FileSystemManager _instance = FileSystemManager._internal();
// using a factory is important
// because it promises to return _an_ object of this type
// but it doesn't promise to make a new one.
factory FileSystemManager() {
return _instance();
}
// This named constructor is the "real" constructor
// It'll be called exactly once, by the static property assignment above
// it's also private, so it can only be called in this class
FileSystemManager._internal() {
// initialization logic
}
// rest of class as normal, for example:
void openFile() {}
void writeFile() {}
}
class Singleton {
static final Singleton _singleton = Singleton._internal();
factory Singleton() {
return _singleton;
}
Singleton._internal();
}
main() {
var s1 = Singleton();
var s2 = Singleton();
print(identical(s1, s2)); // true
print(s1 == s2); // true
}