Created
April 26, 2012 20:54
-
-
Save atebitftw/2503120 to your computer and use it in GitHub Desktop.
Dart Singleton?
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 MyClass{ | |
static MyClass _ref; | |
static MyClass get context() => _ref == null ? new MyClass() : _ref; | |
factory MyClass(){ | |
if (_ref != null) return _ref; | |
_ref = new MyClass._internal(); | |
return _ref; | |
} | |
MyClass._internal(){} | |
} |
Looks good to me. :)
Nice
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The factory constructor acts as a proxy in this case, and simply returns the same object (_ref) if it is already initialized.
Using the underscore on the named instance constructor MyClass._internal() is supposed to prevent it's usage outside of library boundaries.
So I think I have a good singleton pattern here, at least outside of library boundaries.