本文是 FlutterTips 项目的第一篇,欢迎你们在同性交友社区 Star 本项目,谢谢你们!git
单例模式是平常开发中最经常使用的设计模式之一,在工做中各类 Manager 和 SharedInstance 层出不穷。本文就分享一下单例在 Flutter 中的使用。github
首先咱们先看一下,在 Flutter 中如何实现一个单例。数据库
class SomeSharedInstance {
// 单例公开访问点
factory SomeSharedInstance() =>_sharedInstance()
// 静态私有成员,没有初始化
static SomeSharedInstance _instance;
// 私有构造函数
SomeSharedInstance._() {
// 具体初始化代码
}
// 静态、同步、私有访问点
static SomeSharedInstance _sharedInstance() {
if (_instance == null) {
_instance = SomeSharedInstance._();
}
return _instance;
}
}
复制代码
如上所示,咱们首先定义了一个类 SomeSharedInstance
,在业务中咱们经过定义 SomeSharedInstance()
方法返回一个对单例的懒加载:若是不存在则初始化,若是存在则返回。由于 Dart
是一个单线程的语言,因此其调用是线程安全的,这意味着咱们全局有且仅有一个 _instance
。设计模式
懒汉模式安全
在类加载时,不建立实例。加载时速度较快,运行时获取实例速度较慢。 上面的例子就是懒汉模式,它适用于绝大多数的场景。函数
饿汉模式工具
在类加载时,直接进行实例的建立。加载时获取实例速度较慢,运行时速度较快。对上面的代码作一个小的改动便可。spa
class SomeSharedInstance {
// 单例公开访问点
factory SomeSharedInstance() =>_sharedInstance()
// 静态私有成员,没有初始化
static SomeSharedInstance _instance = SomeSharedInstance._();
// 私有构造函数
SomeSharedInstance._() {
// 具体初始化代码
}
// 静态、同步、私有访问点
static SomeSharedInstance _sharedInstance() {
return _instance;
}
}
复制代码