「Flutter/dart/singleton」の版間の差分
提供: 初心者エンジニアの簡易メモ
| 行2: | 行2: | ||
class SingletonHoge { | class SingletonHoge { | ||
String name = ""; | String name = ""; | ||
| − | + | static final SingletonHoge _singleton = SingletonHoge._internal(); | |
| − | static final SingletonHoge | + | factory SingletonHoge() { |
| − | + | return _singleton; | |
| − | return | + | } |
| + | SingletonHoge._internal() { | ||
| + | // init | ||
} | } | ||
} | } | ||
| + | |||
</pre> | </pre> | ||
<pre> | <pre> | ||
| − | SingletonHoge hoge = SingletonHoge | + | SingletonHoge hoge = SingletonHoge(); |
print (hoge.name); // "" | print (hoge.name); // "" | ||
hoge.name = "taro"; | hoge.name = "taro"; | ||
2019年12月2日 (月) 22:25時点における版
class SingletonHoge {
String name = "";
static final SingletonHoge _singleton = SingletonHoge._internal();
factory SingletonHoge() {
return _singleton;
}
SingletonHoge._internal() {
// init
}
}
SingletonHoge hoge = SingletonHoge(); print (hoge.name); // "" hoge.name = "taro"; print (hoge.name); // "taro"
https://stackoverflow.com/questions/12649573/how-do-you-build-a-singleton-in-dart
