单例设计模式-java

/**
 * 饿汉式
 */
class SingletonHungery{
    private static SingletonHungery s = new SingletonHungery();
    private SingletonHungery(){

    }
    public static SingletonHungery getInstance(){
        return s;
    }
}

/**
 * 懒汉式
 */

class SingletonLazy{
    private static SingletonLazy s;
    private SingletonLazy(){

    }
    public static SingletonLazy getInstance(){
        if(s == null) {
            s = new SingletonLazy();
        }
        return s;
    }
}

public class SingletonDemo {
    public static void main(String[] args) {
        SingletonHungery s1 = SingletonHungery.getInstance();
        SingletonHungery ss1 = SingletonHungery.getInstance();
        System.out.println(s1 == ss1);

        SingletonLazy s2 = SingletonLazy.getInstance();
        SingletonLazy ss2 = SingletonLazy.getInstance();
        System.out.println(s2 == ss2);
    }

}

 

posted on 2018-07-31 09:49  可豆豆  阅读(87)  评论(0编辑  收藏  举报

导航