一个理解“单例模式”最好的例子

Posted on 2006-11-26 13:57 Jaunt 阅读(757) 评论(0)  编辑  收藏 所属分类: 咖啡Java

原文出处: http://www.javatang.com/archives/2006/06/27/512049.html
编辑: Jaunt
声明: 请维持文章的完整性任意转载

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


只有注册用户登录后才能发表评论。


网站导航: