简单理解单例模式写法(第一篇)

来源:互联网 发布:热敏打印纸软件 编辑:程序博客网 时间:2024/06/05 15:38
单例模式:
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);

}

0 0
原创粉丝点击