LoginSignup
0
0

More than 3 years have passed since last update.

Singletonパターン

Last updated at Posted at 2020-08-18

Singletonパターン

インスタンスが1つしか存在しないことを保証するパターンのこと。

Singletonの役

Singletonの役は唯一のインスタンスを得るためのstaticメソッドを持つ。
このメソッドはいつも同じインスタンスを返す。

package singleton;

public class Singleton {
    private static Singleton singleton = new Singleton();

    // コンストラクタをprivateにすることでクラス外からコンストラクタを呼び出すことを禁止する
    private Singleton() {
        System.out.println("インスタンスを生成しました");
    }

    // インスタンスを返すstaticなメソッドを提供する
    public static Singleton getInstance() {
        return singleton;
    }
}

呼び出し元

package singleton;

public class Main {

    public static void main(String[] args) {
        System.out.println("Start");
        Singleton obj1 = Singleton.getInstance();
        Singleton obj2 = Singleton.getInstance();
        if (obj1 == obj2) {
            System.out.println("同じインスタンス");
        } else {
            System.out.println("同じインスタンスではない");
        }
        System.out.println("End");
    }
}

// Start
// インスタンスを生成しました
// 同じインスタンス
// End

サンプル

package singleton;

public class TicketMaker {
    private static TicketMaker ticketMaker = new TicketMaker();
    private int ticket = 1000;
    private TicketMaker() {
    }

    public static TicketMaker getInstance() {
        return ticketMaker;
    }

    // 複数のスレッドから呼び出せれた場合でも正しく動作するようsyncronizedを付与
    public synchronized int getNextTiketNumber() {
        return ticket++;
    }
}

インスタンスの数が3つに限定されているクラス

package singleton;

public class Triple {
    private static Triple[] triples = new Triple[] {
            new Triple(0),
            new Triple(1),
            new Triple(2),
    };

    private int id;

    private Triple(int id) {
        System.out.println("The instance" + id + " is created");
        this.id = id;
    }

    public static Triple getInstance(int id) {
        return triples[id];
    }

    public String toString() {
        return "[Triple id = " + id + "]";
    }

}
package singleton;

public class Main {

    public static void main(String[] args) {
        System.out.println("Start");
        for (int i = 0; i < 9; i++) {
            Triple triple = Triple.getInstance(i % 3);
            System.out.println(i + ":" + triple);

        }
        System.out.println("End");

    }
}
// Start
// The instance0 is created
// The instance1 is created
// The instance2 is created
// 0:[Triple id = 0]
// 1:[Triple id = 1]
// 2:[Triple id = 2]
// 3:[Triple id = 0]
// 4:[Triple id = 1]
// 5:[Triple id = 2]
// 6:[Triple id = 0]
// 7:[Triple id = 1]
// 8:[Triple id = 2]
// End

こちらを参考にさせていただきました。
増補改訂版Java言語で学ぶデザインパターン入門

0
0
0

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
0
0