设计模式-单例模式(Singleton)

单例模式可以保证为一个类只生成唯一的实例对象。

具体代码:

/**
 * 饿汉式
 */
public class HungrySingleton {
    private HungrySingleton(){}
    private static final HungrySingleton hungrySingleton = new HungrySingleton();
    public static HungrySingleton getInstance(){
        return hungrySingleton;
    }
}
/**
 * 懒汉式
 */
public class LazySingleton {
    private LazySingleton(){}
    private static LazySingleton lazySingleton;
    public static LazySingleton getInstance(){
        if(lazySingleton == null){
            synchronized (LazySingleton.class){
                if(lazySingleton == null){
                    lazySingleton = new LazySingleton();
                }
            }
        }
        return lazySingleton;
    }
}
public class Main {
    public static void main(String[] args) {
        HungrySingleton hungrySingleton = HungrySingleton.getInstance();//饿汉式
        HungrySingleton hungrySingleton1 = HungrySingleton.getInstance();//饿汉式

        LazySingleton lazySingleton = LazySingleton.getInstance();//懒汉式
        LazySingleton lazySingleton1 = LazySingleton.getInstance();//懒汉式

        System.out.println(hungrySingleton.getClass().hashCode());
        System.out.println(hungrySingleton1.getClass().hashCode());
        System.out.println(lazySingleton.getClass().hashCode());
        System.out.println(lazySingleton1.getClass().hashCode());
    }
}

结果:

1163157884
1163157884
1956725890
1956725890

 

源码:https://github.com/qjm201000/design_pattern_singleton.git

posted @ 2018-12-03 10:33  qjm201000  阅读(130)  评论(0编辑  收藏  举报