Created
October 27, 2019 20:43
-
-
Save danielgoncalves/02bee0a6127cbefaae383836495bdfaf to your computer and use it in GitHub Desktop.
Dart Singletons
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
// (!) 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 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
// (!) 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