Skip to content

Instantly share code, notes, and snippets.

@fujimisakari
Last active August 11, 2017 10:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fujimisakari/b38f173158234bad23ca7a47ec8a498d to your computer and use it in GitHub Desktop.
Save fujimisakari/b38f173158234bad23ca7a47ec8a498d to your computer and use it in GitHub Desktop.
Singletonパターン

Singletonパターン

HeadFirstデザインパターン Index

パターンについて

ただ1つだけのオブジェクトが作成されていることを保証します。

HeadFirstデザインパターンでの定義

1つのクラスがただ1つのインスタンスを持つことを保証し インスタンスにアクセスするグローバルポイントを提供する。

パターン構造

singleton_pattern

構成要素
uniqueInstance : getInstanceで生成されたインスタンスを保持しておく静的な変数。
Singleton(コンストラクタ) : スコープをprivateに定義し、getInstanceからのみ生成できるようにする。
getInstance : 唯一のインスタンスを取得できる静的メソッド。呼び出し時にインスタンスが存在しなれば生成する。

サンプル

Singletonクラスを生成する場合(マルチスレッドの場合は別途対策が必要)

Singletonクラス(Singleton)

public class Singleton {
	private static Singleton uniqueInstance;
 
	private Singleton() {}
 
	public static Singleton getInstance() {
		if (uniqueInstance == null) {
			uniqueInstance = new Singleton();
		}
		return uniqueInstance;
	}
 
	// other useful methods here
	public String getDescription() {
		return "I'm a classic Singleton!";
	}
}

実行コード

public class Client {
	public static void main(String[] args) {
		Singleton singleton = Singleton.getInstance();
        System.out.println(singleton.getDescription());
	}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment