第4节:Flutter设计模式

一、单例

参照SharedPreferences

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class SharedPreferences {
SharedPreferences._(this._preferenceCache);

static const String _prefix = 'flutter.';
static SharedPreferences _instance;
static Future<SharedPreferences> getInstance() async {
if (_instance == null) {
final Map<Object, Object> fromSystem =
await _kChannel.invokeMethod('getAll');
assert(fromSystem != null);
// Strip the flutter. prefix from the returned preferences.
final Map<String, Object> preferencesMap = <String, Object>{};
for (String key in fromSystem.keys) {
assert(key.startsWith(_prefix));
preferencesMap[key.substring(_prefix.length)] = fromSystem[key];
}
_instance = SharedPreferences._(preferencesMap);
}
return _instance;
}

创建一个单例的Manager类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Manager {
// 工厂模式
factory Manager() =>_getInstance();
static Manager get instance => _getInstance();

static Manager _instance;
Manager._internal() {
// 初始化
}
static Manager _getInstance() {
if (_instance == null) {
_instance = new Manager._internal();
}
return _instance;
}
}

调用

1
2
3
// 无论如何初始化,取到的都是同一个对象
Manager manager = new Manager();
Manager manager2 = Manager.instance;