-
-
Save slaveofcode/4e670aef53f48b41d748c4ecf2aa0a46 to your computer and use it in GitHub Desktop.
Using Dart's factory constructor feature to implement the singleton pattern
This file contains hidden or 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 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