Skip to content

Instantly share code, notes, and snippets.

@Bujupah
Last active October 14, 2020 18:10
Show Gist options
  • Save Bujupah/cf0fe4b98e39f13bbfbe24ae00dee64f to your computer and use it in GitHub Desktop.
Save Bujupah/cf0fe4b98e39f13bbfbe24ae00dee64f to your computer and use it in GitHub Desktop.
Using Dart's factory constructor to implement the singleton pattern
class MySingleton {
String var1;
int var2;
static MySingleton _instance;
factory MySingleton({String var1, int var2}) {
_instance == null
? print('New instance!')
: print('Old instance!');
_instance ??= MySingleton._internal(var1, var2); // if _instance is null then init it
return _instance;
}
MySingleton._internal([this.var1, this.var2]){
// Todo: Your logic stuff
}
}
final instanceA = MySingleton(var1: 'Yo!', var2: 1); // prints "New instance"
final instanceB = MySingleton(); // prints "Old instance"
final instanceC = MySingleton(); // prints "Old instance"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment