我正在尝试学习 Dart 语言和 flutter。我遇到了以下代码(取自此处:https://github.com/ppicas/flutter-android-background/blob/master/lib/counter_service.dart):
import 'package:flutter/foundation.dart';
import 'counter.dart';
class CounterService {
factory CounterService.instance() => _instance;
CounterService._internal(); <<====================== Why is this line here ? What does it do?
static final _instance = CounterService._internal();
final _counter = Counter();
ValueListenable<int> get count => _counter.count;
void startCounting() {
Stream.periodic(Duration(seconds: 1)).listen((_) {
_counter.increment();
print('Counter incremented: ${_counter.count.value}');
});
}
}
我不明白为什么需要这行代码。我知道我们通过实现私有构造函数来强制返回此类的单个实例,并且唯一的实例是在以下行中创建的。那么,为什么我们真的必须在那里有那条线呢?
如果飞镖专家能对此有所说明,我将不胜感激。谢谢
CounterService._internal();
是一个私有命名构造函数,用于创建对象并且只能在类中调用(隐私)。
factory CounterService.instance() => _instance;
是一个公共命名构造函数,返回一个对象(
CounterService object
)并且可以在类外部调用。
现在问题:
该类的客户端如何创建对象?
答案:他只是调用
CounterService.instance()
,它总是返回一个我们已经从内部私有构造函数实例化的对象。记住!
static final _instance = CounterService._internal();
_instance 是与其类相同类型的私有对象,它是一个 composition
注意:它是使用私有构造函数创建的,而公共构造函数总是返回它。 那么,上面代码的目的是什么?
它的目标是仅返回该类的一个对象,这是对单例设计模式的 符合。
希望对您有帮助。