gpt4 book ai didi

dart - 将参数传递给单例并基于该参数定义成员

转载 作者:行者123 更新时间:2023-12-03 04:20:02 24 4
gpt4 key购买 nike

我需要将参数传递给单例,并根据传递的参数定义类成员。
这是我正在使用的代码实际上不起作用:

class MyService {
static final MyService _singleton = ImapService._internal();

String level;
MyClass _client;

factory MyService({level = 'HIGH'}) {
_singleton.level = level;

return _singleton;
}

MyService._internal() {
if (level == 'LOW') {
_client = new Class1();
} else {
_client = new Class2();
}
}
}
问题在于, MyService._internal()函数始终在 factory之前调用,因此 level变量在该函数中始终为null,而我的代码从不在 If语句中进行。

最佳答案

您想要具有可变状态的单例。那有点合理。
如果在实例上使用状态,则需要有效的初始值。
就像是:

class MyService {
static final MyService _singleton = MyService._internal();
String _level;
MyClass _clientCache;
String get level => level;
set level(String level) {
if (_level != level) {
_level = level;
_clientCache = level == "LOW" ? Class1() : Class2();
}
}
factory MyService({String level = "HIGH"}) => _singleton..level = level;
MyService._internal() : _level = "HIGH", _clientCache = Class1();
}
然后,您也可以将该状态存储在全局变量中。这将允许您懒惰地初始化 _class getter。
就像是:
class MyService {
static final MyService _singleton = const MyService._internal();

static String _level = "HIGH";
static MyClass _clientCache = _classFromLevel(_level);

String get level => _level;
void set level(String level) {
if (_level != level) {
_level = level;
_clientCache = _classFromLevel(level);
}
}

MyClass _client => _clientCache;

factory MyService({level = 'HIGH'}) => _instance..level = level;

const MyService._internal();

static MyClass _classFromLevel(String level) =>
level == "LOW" ? Class1() : Class2();
}
(请考虑您是否真的需要单例。可变的单例对象只是带有所有这些固有问题的荣耀的全局变量。)

关于dart - 将参数传递给单例并基于该参数定义成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63245067/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com