Skip to content

Instantly share code, notes, and snippets.

@danielgoncalves
Created October 27, 2019 20:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielgoncalves/02bee0a6127cbefaae383836495bdfaf to your computer and use it in GitHub Desktop.
Save danielgoncalves/02bee0a6127cbefaae383836495bdfaf to your computer and use it in GitHub Desktop.
Dart Singletons
// (!) This implementation seems to work;
// Trying this in DartPad results in "s = false" and "f = true" as expected.
// This was taken from https://gist.github.com/theburningmonk/6401183
class FooBar {
static final FooBar _instance = new FooBar._internal();
factory FooBar() => _instance;
FooBar._internal() {
// initialization logic here
}
}
class SpamEggs {}
void main() {
var s1 = SpamEggs();
var s2 = SpamEggs();
var f1 = FooBar();
var f2 = FooBar();
print('s = ${identical(s1, s2)}');
print('f = ${identical(f1, f2)}');
}
// (!) This singleton implementation doesn't seem to work;
// Trying this in DartPad results in "s = false" and "f = false" which is unexpected.
class FooBar {
static final FooBar _instance = FooBar.getInstance();
FooBar.getInstance();
factory FooBar() => _instance;
}
class SpamEggs {}
void main() {
var s1 = SpamEggs();
var s2 = SpamEggs();
var f1 = FooBar.getInstance();
var f2 = FooBar.getInstance();
print('s = ${identical(s1, s2)}');
print('f = ${identical(f1, f2)}');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment