Skip to content

Instantly share code, notes, and snippets.

@taznica
Created April 23, 2022 09:42
Show Gist options
  • Save taznica/6308669c891b61b89e26bae874d8feb7 to your computer and use it in GitHub Desktop.
Save taznica/6308669c891b61b89e26bae874d8feb7 to your computer and use it in GitHub Desktop.
class Singleton {
static final Singleton _singleton = Singleton._();
factory Singleton() {
return _singleton;
}
Singleton._();
}
@taznica
Copy link
Author

taznica commented Apr 23, 2022

static final Singleton _singleton = Singleton._();
  • static
    • クラス変数
    • クラスにつき1つだけ生成される
  • final
    • 1度だけ初期化され、初期化後は変更されない
    • 初期化時のみ、6行目で定義したコンストラクタ Singleton._() が呼ばれて _singleton に代入され、2度目以降は_singleton は代入(変更)されない
factory Singleton() {
  return _singleton;
}
  • factory
    • factory constructor
    • 通常のコンストラクタとは異なり、自動的にインスタンスの生成はされず、明示的にインスタンスを生成する必要がある
    • -> 新しいインスタンスを生成したくない場合に、明示的にインスタンスを生成できたり、あらかじめ生成しておいたインスタンスを返すようにできたりする
    • 2行目で生成されたまたはキャッシュされていたインスタンスを返す
Singleton._();
  • Singleton._();
    • private な named constructor を定義している
    • _から始まると private constructor になる
    • named constructor なので _internal() などでもいい
    • private constructor なのでクラス内部からしか呼ばれない
    • 2行目で1度だけ呼ばれる
References

https://stackoverflow.com/a/12649574
https://flutterbyexample.com/lesson/singletons

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment