Skip to content

Instantly share code, notes, and snippets.

@georgesboris
Created May 27, 2020 13:07
Show Gist options
  • Save georgesboris/91dda48916d7b3dc5e54ae97a61e1a45 to your computer and use it in GitHub Desktop.
Save georgesboris/91dda48916d7b3dc5e54ae97a61e1a45 to your computer and use it in GitHub Desktop.
Dart singletons
class SingletonValueNoFactory {
static SingletonValueNoFactory _instance;
final dynamic value;
SingletonValueNoFactory._internal(this.value);
static SingletonValueNoFactory getInstance(value) {
return _instance ??= SingletonValueNoFactory._internal(value);
}
}
class SingletonValue {
static SingletonValue _instance;
final dynamic value;
SingletonValue._internal(this.value);
factory SingletonValue(value) {
return _instance ??= SingletonValue._internal(value);
}
}
void main() {
print(SingletonValueNoFactory.getInstance("no factory").value);
print(SingletonValueNoFactory.getInstance("no factory - changed").value);
print(SingletonValueNoFactory._internal("no factory - breaking singleton").value);
print(SingletonValue("factory").value);
print(SingletonValue("factory - changed").value);
print(SingletonValue._internal("factory - breaking singleton").value);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment