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;
}
}
package com.ermu.gof.singleton;
/**
* @author:xusonglin
* ===============================
* Created with IDEA.
* Date:2019/1/13
* Time:21:27
* 双重判断
* ================================
*/
public class DoubleSynchronizedLazySingleton {
/**
* volatile 禁止指令重排序
* 因为下面代码有重复地方
*/
private static volatile DoubleSynchronizedLazySingleton singleton = null;
public DoubleSynchronizedLazySingleton() {
}
private static DoubleSynchronizedLazySingleton getSingleton(){
if(null == singleton){
synchronized (DoubleSynchronizedLazySingleton.class){
if (null == singleton){
return new DoubleSynchronizedLazySingleton();
}
return singleton;
}
}
return singleton;
}
}