Skip to content

Instantly share code, notes, and snippets.

@atebitftw
Created April 26, 2012 20:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save atebitftw/2503120 to your computer and use it in GitHub Desktop.
Save atebitftw/2503120 to your computer and use it in GitHub Desktop.
Dart Singleton?
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(){}
}
@MarkBennett
Copy link

So is _internal() meant to be an internal constructor? I had no idea that would work but it makes sense to me.

What does the factory keyword do in this context? I've only seen it in relation to interfaces.

@atebitftw
Copy link
Author

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.

@MarkBennett
Copy link

Looks good to me. :)

@adam-singer
Copy link

Nice

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment