Singletonはたった一人
今日はシステム的な方のお話。
「Singleton」ってなんぞや、ということを最近ようやく理解したので、忘れないうちにメモメモ。
・Singletonなクラスはひとつしか作られないことを保証する。
・DBのコネクションとか、無駄に複数生成したらパフォーマンスに影響しそうなところに使うとお役立ち。
・覚え方は「single + ton」だから、たったひとつ!
「ton」はとりあえず無視!
※英語の接尾語調べてみたが、ちっとも引っかからなかった。
※ちなみに、twin(双子)の対義語らしい
Javaで書くとこんな感じ↓
public static class Singleton {
private Singleton singleton;
private Singleton() {
// 処理なし
}
public static Singleton getInstance() {
if (this.singleton == null) {
this.singleton = new Singleton();
}
return this.singleton;
}
}
private Singleton singleton;
private Singleton() {
// 処理なし
}
public static Singleton getInstance() {
if (this.singleton == null) {
this.singleton = new Singleton();
}
return this.singleton;
}
}
実践で使うことは、まだまだあんまり無さそうですが、ね。
覚えておくに越したことはない。
しかし、英語の部分がスッキリしない……。