认识各种单例模式第一篇(开发篇)

单例模式:
1.简单单例模式
2.懒汉模式
3.DCL模式(线程安全)
4.静态内部类单例模式
5.枚举单例
6.使用容器实现单例模式


1.简单单例模式:
private static final Object instance = new Object();
private Object(){

}
public static Object getInstance(){
return instance;
}
2.懒汉模式:
private static Object instance;
private Object(){

}
public static synchronized Object getInstance(){
if(instance == null){
instance = new Object();
}
}
3.DCL模式(线程安全):
private static Object instance;
private Object(){

}
public static Object getInstance(){
if(instance == null){
synchronized(this){
if(instance == null){
instance = new Object();
}
}
}
}
4.静态内部类单例模式
private Object(){

}
public static Object getInstance{
return ObjectHolder.instance;
}
private static class ObjectHolder {
private static final Object instance = new Object();
}
5.枚举单例
public enum singletonEnum {
INSTANCE;
}
6.使用容器实现单例模式
private static Map<String, Object> objMap = new HashMap<String, Object>();
public static void registerService(String key, Object instance){
if(!objMap.containsKey(key)){
objMap.put(key, instance);
}
}
public static Object getService(String key){
return objMap.get(key);
}

你可能感兴趣的:(认识各种单例模式第一篇(开发篇))