面向对象设计模式之单例模式
2019-03-08 本文已影响0人
严中辉
单例对象的类必须保证只有一个实例存在。
/**
* 饿汉模式
*/
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)实现单例
*/
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);
}
}