Skip to content

Instantly share code, notes, and snippets.

@m-cakir
Forked from theburningmonk/singleton.dart
Created November 23, 2019 22:43
Show Gist options
  • Save m-cakir/d4caa71f9365cb46aa4779025dbabf98 to your computer and use it in GitHub Desktop.
Save m-cakir/d4caa71f9365cb46aa4779025dbabf98 to your computer and use it in GitHub Desktop.
Using Dart's factory constructor feature to implement the singleton pattern
class MyClass {
static final MyClass _singleton = new MyClass._internal();
factory MyClass() {
return _singleton;
}
MyClass._internal() {
... // initialization logic here
}
... // rest of the class
}
// consuming code
MyClass myObj = new MyClass(); // get back the singleton
...
// another piece of consuming code
MyClass myObj = new MyClass(); // still getting back the singleton
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment