単純なSingleton単一モード

1504 ワード

SingletonTest.java :


public class SingletonTest {
    public static void main(String[] args) {
        Singleton s1 = Singleton.getInstance();
        Singleton s2 = Singleton.getInstance();
        System.out.println("s1=s2?" + (s1==s2));
        System.out.println("s1.getNextID = " + s1.getNextID());
        System.out.println("s2.getNextID = " + s2.getNextID());
        System.out.println("s1.getNextID = " + s1.getNextID());
        System.out.println("s1.getNextID = " + s1.getNextID());
        System.out.println("s2.getNextID = " + s2.getNextID());
        System.out.println("s2.getNextID = " + s2.getNextID());
    }
} 
class Singleton {
    private static int nextID = 0;
    private static Singleton instance = null;

    private Singleton() {};

    public static synchronized Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
    // inside data
    public synchronized int getNextID() {
        return ++nextID;
    }
}

 :

s1=s2?true
s1.getNextID = 1
s2.getNextID = 2
s1.getNextID = 3
s1.getNextID = 4
s2.getNextID = 5
s2.getNextID = 6