我收集了以下使用引數在 dart 中創建單例的理解
class Foo extends ChangeNotifier {
late String channel;
void instanceMemberFunction () {
print('Foo created with channel $channel')
}
static final Foo _instance = Foo._internal();
Foo._internal() {
instanceMemberFunction();
}
factory Foo({
required String channel
}) {
_instance.channel = channel;
return _instance;
}
}
我像這樣呼叫實體
Foo({channel: "bar"})
現在我想要一些作業,如果我使用
Foo({channel: "baz"})
然后創建一個新實體,在這種情況下可以銷毀舊實體。我怎樣才能在飛鏢中實作這一目標?
uj5u.com熱心網友回復:
似乎您復制了一些現有的示例來創建單例,而沒有完全理解它在做什么以及為什么。核心部分是:
- 單個實體存盤在全域或
static變數中。 - 該類具有一個或多個
factory回傳該全域/static變數的公共建構式,并在必要時對其進行初始化。 - 該類的所有其他建構式都是私有的,以強制消費者通過
factory建構式。
因此,如果您希望factory建構式根據其引數替換其單例,則需要:
- 讓您的
factory建構式檢查引數是否適用于現有實體。如果是,則回傳現有實體。如果沒有(或者如果沒有現有實體),則創建并回傳一個新實體。 - 由于您需要檢查現有實體是否已初始化,因此將其設為可空。(您也可以將其初始化為非空標記值,例如
Foo._internal(channel: ''). - 將引數傳遞給私有建構式。
class Foo extends ChangeNotifier {
final String channel;
void instanceMemberFunction () {
print('Foo created with channel $channel');
}
static Foo? _instance;
Foo._internal({required this.channel}) {
instanceMemberFunction();
}
factory Foo({required String channel}) {
if (channel != _instance?.channel) {
_instance = Foo._internal(channel: channel);
}
return _instance!;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/330685.html
