dart_in_action/15_design_pattern_singleton...

33 lines
796 B
Dart
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
单例模式Singleton Pattern
意图:保证一个类仅有一个实例,并提供一个访问它的全局访问点。
主要解决:一个全局使用的类频繁地创建与销毁。
何时使用:当您想控制实例数目,节省系统资源的时候。
如何解决:判断系统是否已经有这个单例,如果有则返回,如果没有则创建。
*/
main(List<String> args) {
var s1 = Singleton();
var s2 = Singleton();
print(identical(s1, s2));
print(s1 == s2);
}
//////////////////////////////////////////////////////////////////
///
/// 实现单例模式
///
class Singleton {
// 单例
static final Singleton _instance = Singleton._();
// 私有构造器
Singleton._();
// 工厂方法
factory Singleton() {
return _instance;
}
}