Created
June 3, 2019 15:41
-
-
Save komapeb/650d4c565cfe604d8983c16b66e9057b to your computer and use it in GitHub Desktop.
Simple Singleton pattern implementation in Dart, without using the ugly Singleton.instance or Singleton.getInstance(). Just Singleton() returns the singleton instance. Beautiful.
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
// Singleton logic | |
class Singleton { | |
// This makes sure Singleton() always returns the same instance | |
static final Singleton _instance = Singleton._(); | |
Singleton._(); | |
factory Singleton() { | |
return _instance; | |
} | |
// define any props, methods you want | |
int port = 53; | |
} | |
// End Singleton logic | |
// some tests | |
void main() { | |
var a = Singleton(); | |
print(a.port); // 53 | |
var b = Singleton(); | |
b.port = 007; | |
print(a.port); // 007 | |
b.port = 123; | |
print(a.port); // 123 | |
a.port = 433; | |
print(b.port); // 433 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment