Last active
April 25, 2020 11:17
-
-
Save publicJorn/76b00f187c5abfe1fe52c19206d0d3e1 to your computer and use it in GitHub Desktop.
Dart singleton explained. Try it out in https://dartpad.dev/
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
import 'dart:math'; | |
class Randy { | |
String say; | |
int nr; | |
// Note: Randy constructs with a RANDOM number | |
Randy(say) { | |
this.say = say; | |
int random = Random().nextInt(999); | |
print('Construct Randy with number: $random'); | |
this.nr = random; | |
} | |
String getSome() { | |
return '$say: $nr!'; | |
} | |
} | |
// Single is a singleton class | |
class Single { | |
// It has a property that will be an instance of a normal class | |
Randy randy; | |
// This construct will make sure only 1 instance can ever exist | |
Single._singleton(); | |
static final Single _instance = Single._singleton(); | |
// The singleton factory method allows to pass initialisation to the singleton | |
factory Single(String say) { | |
// Here initialise any instance properties on creation of singleton | |
_instance.randy = Randy(say); | |
return _instance; | |
} | |
} | |
void main() { | |
// The first call will work as expected, | |
// printing `First call: <random number>` | |
Single single = Single('First init'); | |
print(single.randy.getSome()); | |
// However when initialising again, even with a new variable (single2) | |
// the singleton properties are overwritten and BOTH variables will | |
// produce the same output | |
Single single2 = Single('Second init'); | |
// The second init overwrites the first | |
print(single.randy.getSome()); | |
print(single2.randy.getSome()); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The
Single
singleton class in this example uses a factory constructor. See other examples in this post: https://stackoverflow.com/a/55348216/1783174