什么是单例
单例模式,是一种常用的软件设计模式。在它的核心结构中只包含一个被称为单例的特殊类。
单例的应用场景
通过单例模式可以保证系统中,应用该模式的类一个类只有一个实例。即一个类只有一个对象实例。
单例模式是设计模式中最简单的形式之一。这一模式的目的是使得类的一个对象成为系统中的唯一实例。
要实现这一点,可以从客户端对其进行实例化开始。因此需要用一种只允许生成对象类的唯一实例的机制,“阻止”所有想要生成对象的访问。
- 工厂构造 Factory constructor
- 静态变量 Static field with getter
- 静态变量Static field 常量
- 常量和工厂构造 const constructor & factory
dart中的单例
工厂构造 Factory constructor
class Singleton{
Singleton._privateConstructor();
static final Singleton _instance = Singleton._privateConstructor();
factory Singleton(){
return _instance;
}
}
静态变量 Static field with getter
class Singleton{
Singleton._privateConstructor();
static final Singleton _instance = Singleton._privateConstructor();
static Singleton get instance { return _instance;}
}
静态变量Static field
class Singleton {
Singleton._privateConstructor();
static final Singleton instance = Singleton._privateConstructor();
}
常量和工厂构造 const constructor & factory
class Singleton {
factory Singleton() =>
const Singleton._internal_();
const Singleton._internal_();
}
print(new Singleton() == new Singleton());