Skip to content

Instantly share code, notes, and snippets.

@karthikAdaptavant
Forked from theburningmonk/singleton.dart
Created April 7, 2020 14:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save karthikAdaptavant/8f34d3890287ed1794bc6f50bf562a6a to your computer and use it in GitHub Desktop.
Save karthikAdaptavant/8f34d3890287ed1794bc6f50bf562a6a 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