Skip to content

Instantly share code, notes, and snippets.

@komapeb
Created June 3, 2019 15:41
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 komapeb/650d4c565cfe604d8983c16b66e9057b to your computer and use it in GitHub Desktop.
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.
// 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