6
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Singletonパターンの実装方法について

Posted at

Singletonパターンについて

Gofの23種類のデザインパターン
で最も使用頻度の高いパターンが
「Singleton」
になりますが、こちらについて解説していきたいと思います。

Singletonパターンとは?

インスタンスを1つしか作れないようなクラスを実装するデザインパターン
になります。

クラスは不用意に生成するとメモリの仕様容量が膨れ上がったり
異なるインスタンスを扱うこととなり、可読性やメンテナンス性が大きく低下する要因になります。
ならば全てのメソッドやフィールドをstaticにすればいいのでは?
と思うかもしれませんが、
staticな変数は、

・継承ができない
・抽象メソッドが作成できない
・すなわちポリモーフィックな実装ができない
・再初期化ができない。

等のオブジェクト指向の手法が使用できないというデメリットがあります

実装方法

それでは、java言語でSingletonを実装してみたいと思います。

main
public static void main(String[] args) {
		Singleton instance1 = Singleton.getInstance();
		Singleton instance2 = Singleton.getInstance();
		if (instance1 == instance2) {
			System.out.println("instance1 = instance2");
		} else {
			System.out.println("instance1 != instance2");
		}		
}
Singleton実装1
public class Singleton {
	private static Singleton singleton = new Singleton();
	private Singleton() {
		System.out.println("インスタンスを作成しました");
	}
    //getメソッドを使用してインスタンスを生成する
	public static Singleton getInstance() {
		return singleton;
	}
}
Singleton実装2
class Singleton {
    private Singleton(){
        System.out.println("インスタンスを作成しました");
    }
    public static Singleton getInstace() {
        return SingletonHolder.INSTANCE;
    }
    private static class SingletonHolder {
        private static final Singleton INSTANCE = new Singleton();
    }
}

ポイントは、
・コンストラクタをprivate staticで定義して
コンストラクタを直接扱えないようにすると同時に、クラスの初期化時にインスタンスを生成する
・getInstanceメソッドを用意して、インスタンスを使用可能にする。
になります。

結果は、

main
    "instance1 = instance2"

となり、インスタンスが1つのみ作成されることが確認されます。

参考文献:

参考URL:

著者: K.K (株式会社ウィズツーワン)

6
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?