Last active
August 15, 2019 11:51
-
-
Save agiletelescope/fe4fce7aafdceed00d00c3f1db9ecf54 to your computer and use it in GitHub Desktop.
Singleton classes in dart from dartpad
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 MySingleton { | |
int resource = 5; | |
// Singleton pattern | |
static final MySingleton _singleton = new MySingleton._internal(); | |
factory MySingleton({int newResource}) { | |
// Called everytime an object is created. | |
// If an instance of the class already exists, then returns the existing reference, | |
// else creates a new reference and returns it. | |
print ("singlton factory constructor"); | |
if (newResource != null) _singleton.resource = newResource; | |
return _singleton; | |
} | |
// Name doesn't have to be _internal, just a function private to the class | |
MySingleton._internal() { | |
// This is called only the first time | |
print ("private internal function"); | |
} | |
// Getter | |
get getResource => resource; | |
// Setter | |
set setResource(int newResource) { | |
resource = newResource; | |
} | |
} | |
main() { | |
print ("First call"); | |
MySingleton a = new MySingleton(newResource: 4); | |
print (a.getResource); | |
print (""); | |
print ("Second call"); | |
// New just gets the earlier reference | |
MySingleton b = new MySingleton(); | |
print (a.getResource); | |
print (b.getResource); | |
print ("Setting a new value using the setter"); | |
b.setResource = 9; | |
print (a.getResource); | |
print (b.getResource); | |
print (""); | |
print ("Third call"); | |
MySingleton c = new MySingleton(); | |
print (a.getResource); | |
print (b.getResource); | |
print (c.getResource); | |
print (""); | |
print ("Fourth call, with constructor initialization"); | |
MySingleton d = new MySingleton(newResource: 10); | |
print (a.getResource); | |
print (b.getResource); | |
print (c.getResource); | |
print (d.getResource); | |
} | |
/// Output: | |
First call | |
singlton factory constructor | |
private internal function | |
4 | |
Second call | |
singlton factory constructor | |
4 | |
4 | |
Setting a new value using the setter | |
9 | |
9 | |
Third call | |
singlton factory constructor | |
9 | |
9 | |
9 | |
Fourth call, with constructor initialization | |
singlton factory constructor | |
10 | |
10 | |
10 | |
10 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment