面向物件設計模式之單例模式
阿新 • • 發佈:2021-01-11
單例物件的類必須保證只有一個例項存在。
餓漢模式
/**
* 餓漢模式
*/
public class HungrySingleton {
private static final HungrySingleton INSTANCE = new HungrySingleton();
private HungrySingleton() {
}
public static HungrySingleton getInstance() {
return INSTANCE;
}
}
懶漢模式
/** * 懶漢模式 */ public class LazySingleton { private static LazySingleton INSTANCE = null; private LazySingleton() { } public static synchronized LazySingleton getInstance() { if (INSTANCE == null) { INSTANCE = new LazySingleton(); } return INSTANCE; } }
Double Check Lock(DLC)實現單例
/** * Double Check Lock(DLC)實現單例 */ public class SingletonDCL { private static volatile SingletonDCL INSTANCE = null; private SingletonDCL() { } public static SingletonDCL getInstance() { if (INSTANCE == null) { synchronized (SingletonDCL.class) { if (INSTANCE == null) { INSTANCE = new SingletonDCL(); } } } return INSTANCE; } }
靜態內部類單例模式
/**
* 靜態內部類單例模式
*/
public class Singleton {
public Singleton() {
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
}
列舉單例
/**
* 列舉單例
*/
public enum SingletonEnum {
INSTANCE;
public void doSomething() {
}
}
杜絕單例物件在反序列化時重新生成物件
/**
* 杜絕單例物件在反序列化時重新生成物件
*/
public final class SingletonSerializable implements Serializable {
private static final long serialVersionUID = 0L;
private static final SingletonSerializable INSTANCE = new SingletonSerializable();
private SingletonSerializable() {
}
public static SingletonSerializable getInstance() {
return INSTANCE;
}
private Object readResolve() throws ObjectStreamException {
return INSTANCE;
}
}
使用容器實現單例模式
/**
* 使用容器實現單例模式
*/
public class SingletonManager {
private static Map<String, Object> objectMap = new HashMap<>();
public SingletonManager() {
}
public static void registerService(String key, Object instance) {
if (!objectMap.containsKey(key)) {
objectMap.put(key, instance);
}
}
public static Object getService(String key) {
return objectMap.get(key);
}
}