Dart常见单例模式
工厂构造函数
class AMTool {
static final AMTool _singleton = AMTool._init();
factory AMTool() {
return _singleton;
}
AMTool._init();
}
测试
var t1 = AMTool();
var t2 = AMTool();
print(identical(t1, t2));//打印true
静态属性
class AMTool {
AMTool._init();
static final AMTool instance = AMTool._init();
}
测试
var t1 = AMTool.instance;
var t2 = AMTool.instance;
print(identical(t1, t2));///打印true
这里的私有的下划线方法目的是,当你直接调用AMTool的时候,会提示The class 'AMTool' doesn't have a default constructor.
共有 0 条评论