Last active
October 14, 2020 18:10
-
-
Save Bujupah/cf0fe4b98e39f13bbfbe24ae00dee64f to your computer and use it in GitHub Desktop.
Using Dart's factory constructor to implement the singleton pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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