1,单例设计模式
保证程序中只有一个实例。
1.1,饿汉(程序一运行,就开始初始化)
public class Single {
private static Single mIntance = new Single();
private Single(){
}
public static Single getIntance(){
return mIntance;
}
}
1.2,懒汉
方案1:线程不安全
public class Single {
private static Single mIntance ;
private Single(){
}
public static Single getIntance(){
if (mIntance==null){
mIntance = new Single();
}
return mIntance;
}
}
方案2:线程安全,但是效率很低,每次getIntance 都需要经过同步锁的判断
public class Single {
private static Single mIntance ;
private Single(){
}
public static synchronized Single getIntance(){
if (mIntance==null){
mIntance = new Single();
}
return mIntance;
}
}
方案3:线程安全,效率也提高了,但是没有避免(1)执行顺序 (2)线程的不可见
可使用volatile 关键字 解决
public class Single {
//private static Single mIntance ;
private static volatile Single mIntance ;
private Single(){
}
public static Single getIntance(){
if (mIntance==null){
synchronized (Single.class){
if (mIntance==null){
mIntance=new Single();
}
}
}
return mIntance;
}
}
1.4 静态内部类实现单例
public class Single {
public static Single getIntance (){
return SingleHolder.mIntance;
}
private static class SingleHolder{
static final Single mIntance = new Single();
}
}
1.5 容器
private static Map<String,Single> objMap = new HashMap<String,Single>();
public static void registerService(String key, Single instance) {
if (!objMap.containsKey(key) ) {
objMap.put(key, instance) ;
}
}
public static Single getService(String key) {
return objMap.get(key) ;
}
网友评论