单例模式确保只创建一个类的实例。我如何在达特建立这个?
当前回答
下面是在Dart中创建单例对象的几种不同方法的比较。
1. 工厂构造函数
class SingletonOne {
SingletonOne._privateConstructor();
static final SingletonOne _instance = SingletonOne._privateConstructor();
factory SingletonOne() {
return _instance;
}
}
2. 带有getter的静态字段
class SingletonTwo {
SingletonTwo._privateConstructor();
static final SingletonTwo _instance = SingletonTwo._privateConstructor();
static SingletonTwo get instance => _instance;
}
3.静态字段
class SingletonThree {
SingletonThree._privateConstructor();
static final SingletonThree instance = SingletonThree._privateConstructor();
}
如何实例化
上面的单例是这样实例化的:
SingletonOne one = SingletonOne();
SingletonTwo two = SingletonTwo.instance;
SingletonThree three = SingletonThree.instance;
注意:
我最初是把这个作为一个问题来问的,但发现上面所有的方法都是有效的,选择在很大程度上取决于个人喜好。
其他回答
因为我不太喜欢使用new关键字或其他构造函数,比如对单例对象的调用,我更喜欢使用一个名为inst的静态getter:
// the singleton class
class Dao {
// singleton boilerplate
Dao._internal() {}
static final Dao _singleton = new Dao._internal();
static get inst => _singleton;
// business logic
void greet() => print("Hello from singleton");
}
使用示例:
Dao.inst.greet(); // call a method
// Dao x = new Dao(); // compiler error: Method not found: 'Dao'
// verify that there only exists one and only one instance
assert(identical(Dao.inst, Dao.inst));
你可以只使用Constant构造函数。
class Singleton {
const Singleton(); //Constant constructor
void hello() { print('Hello world'); }
}
例子:
Singleton s = const Singleton();
s.hello(); //Hello world
根据文件:
恒定的构造函数 如果类生成永不更改的对象,则可以使这些对象成为编译时常量。为此,定义一个const构造函数,并确保所有实例变量都是final变量。
使用空安全操作符和工厂构造函数可以更好地创建单例对象。
class Singleton {
static Singleton? _instance;
Singleton._internal();
factory Singleton() => _instance ??= Singleton._internal();
void someMethod() {
print("someMethod Called");
}
}
用法:
void main() {
Singleton object = Singleton();
object.someMethod(); /// Output: someMethod Called
}
注意:? ?是一个Null感知操作符,如果左边值为Null,它将返回右边的值,这意味着在我们的例子中_instance ??Singleton._internal();, Singleton._internal()将在第一次调用object时返回,rest _instance将返回。
我在dart和之前的Swift上使用这个简单的模式。我喜欢它的简洁和只有一种使用方式。
class Singleton {
static Singleton shared = Singleton._init();
Singleton._init() {
// init work here
}
void doSomething() {
}
}
Singleton.shared.doSomething();
从Dart 2.13版本开始,就很容易用late关键字了。Late关键字允许我们延迟实例化对象。
作为一个例子,你可以看到:
class LazySingletonExample {
LazySingletonExample._() {
print('instance created.');
}
static late final LazySingletonExample instance = LazySingletonExample._();
}
注意:请记住,当你调用lazy instance field时,它只会被实例化一次。