Last active
July 26, 2021 09:42
-
-
Save riscait/7d8512ad4133816f04248effd52a8426 to your computer and use it in GitHub Desktop.
Dart Singleton Class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// Factory Constructorを使ったシングルトンクラスの定義方法 | |
class FactorySinglton { | |
/// 初めてインスタンス化するときにfactoryコンストラクタから使用する、Privateなコンストラクタ | |
FactorySinglton._() { | |
print('FactorySingleton Constructed'); | |
} | |
/// シングルトンを実現するインスタンスを提供 | |
factory FactorySinglton.instance() => _instance; | |
/// インスタンスのキャッシュ | |
static final FactorySinglton _instance = FactorySinglton._(); | |
String name = ''; | |
} | |
/// Staticプロパティを使ったシングルトンクラスの定義方法 | |
class StaticSingleton { | |
/// 初めてインスタンス化するときに使用する、Privateなコンストラクタ。 | |
StaticSingleton._() { | |
print('StaticSingleton Constructed'); | |
} | |
/// 初回参照時にインスタンスのキャッシュを作成して保持する。 | |
static final StaticSingleton instance = StaticSingleton._(); | |
String name = ''; | |
} | |
void main() { | |
print('Start main'); | |
print('---'); | |
final exampleA = FactorySinglton.instance(); | |
exampleA.name = 'Apple'; | |
final exampleB = FactorySinglton.instance(); | |
exampleB.name = 'Google'; | |
print(exampleA.name); | |
print(exampleB.name); | |
print(exampleA == exampleB); | |
print('---'); | |
final singletonA = StaticSingleton.instance; | |
singletonA.name = 'Apple'; | |
final singletonB = StaticSingleton.instance; | |
singletonB.name = 'Google'; | |
print(singletonA.name); | |
print(singletonB.name); | |
print(singletonA == singletonB); | |
print('---'); | |
print('End main'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment