设计模式(二):Singleton

Singleton:确保在任何情况下,只会产生一个实例

/**
 * @author:xusonglin
 * ===============================
 * Created with IDEA.
 * Date:2019/1/3
 * Time:21:19
 * 一般单例,类加载的时候就创建实例
 * 饿汉式
 * ================================
 */
public class Singleton {
    private static Singleton instance = new Singleton();
    private Singleton(){
        System.out.println("创建了实例");
    }
    private static Singleton getInstance(){
        return instance;
    }
}
/**
 * @author:xusonglin
 * ===============================
 * Created with IDEA.
 * Date:2019/1/3
 * Time:21:22
 * 懒式模式
 * 在需要的时候才进行创建
 * 有线程安全的问题
 * ================================
 */
public class LazySingleton {
    private static LazySingleton ourInstance = null;

    public static LazySingleton getInstance() {
        if(ourInstance == null){
            ourInstance = new LazySingleton();
        }
        return ourInstance;
    }

    private LazySingleton() {
    }
}
/**
 * @author:xusonglin
 * ===============================
 * Created with IDEA.
 * Date:2019/1/3
 * Time:21:25
 * 在懒式上加锁进行线程安全
 * ================================
 */
public class SynchronizedLazySingleton {
    private static SynchronizedLazySingleton instance = null;

    private SynchronizedLazySingleton() {
    }

    private synchronized SynchronizedLazySingleton getInstance(){
        if (instance == null){
            instance = new SynchronizedLazySingleton();
        }
        return instance;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_22420441/article/details/85722052
今日推荐