单例模式确保只创建一个类的实例。我如何在达特建立这个?
当前回答
我觉得阅读new Singleton()不是很直观。你必须阅读文档才能知道new实际上并没有像通常那样创建一个新实例。
这里有另一种方法来做单例(基本上是Andrew上面说的)。
lib / thing.dart
library thing;
final Thing thing = new Thing._private();
class Thing {
Thing._private() { print('#2'); }
foo() {
print('#3');
}
}
main.dart
import 'package:thing/thing.dart';
main() {
print('#1');
thing.foo();
}
注意,由于Dart的惰性初始化,直到第一次调用getter时才创建单例。
如果你愿意,你也可以在单例类上作为静态getter来实现单例。即的事情。单例,而不是顶级getter。
还可以阅读Bob Nystrom在他的游戏编程模式书中对单身人士的看法。
其他回答
在库中使用全局变量怎么样?
single.dart:
library singleton;
var Singleton = new Impl();
class Impl {
int i;
}
main.dart:
import 'single.dart';
void main() {
var a = Singleton;
var b = Singleton;
a.i = 2;
print(b.i);
}
或者这是不受欢迎的?
单例模式在Java中是必要的,因为在Java中不存在全局变量的概念,但在Dart中似乎不需要绕这么长的路。
由const构造函数和工厂组成的Dart单例
class Singleton {
factory Singleton() =>
Singleton._internal_();
Singleton._internal_();
}
void main() {
print(new Singleton() == new Singleton());
print(identical(new Singleton() , new Singleton()));
}
从Dart 2.13版本开始,就很容易用late关键字了。Late关键字允许我们延迟实例化对象。
作为一个例子,你可以看到:
class LazySingletonExample {
LazySingletonExample._() {
print('instance created.');
}
static late final LazySingletonExample instance = LazySingletonExample._();
}
注意:请记住,当你调用lazy instance field时,它只会被实例化一次。
因为我不太喜欢使用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));
这应该有用。
class GlobalStore {
static GlobalStore _instance;
static GlobalStore get instance {
if(_instance == null)
_instance = new GlobalStore()._();
return _instance;
}
_(){
}
factory GlobalStore()=> instance;
}
推荐文章
- 在PHP5中创建单例设计模式
- 如何改变循环进度指示器的颜色
- InkWell没有显示涟漪效应
- 弹出时强制颤振导航器重新加载状态
- 颤振:扩展vs灵活
- 使用Enum实现单例(Java)
- 由Jon Skeet撰写的《Singleton》澄清
- 错误地使用父数据小部件。扩展小部件必须放置在flex小部件中
- 颤振给容器圆形边界
- Flutter: RenderBox没有布局
- 颤振插件未安装错误;当运行'扑动医生'时
- 我如何“休眠”Dart程序
- 在Flutter app上检查是否有网络连接
- Flutter and google_sign_in plugin: PlatformException(sign_in_failed, com.google.android.gms.common.api.ApiException: 10:, null)
- 如何在扑动中格式化日期时间