1、单例模式
饿汉模式
优点:执行效率高,性能高,没有任何的锁
缺点:某些情况下,可能会造成内存的浪费
public class MyStaticHungrySingleton { private static final MyStaticHungrySingleton myStaticHungrySingleton; static{ myStaticHungrySingleton = new MyStaticHungrySingleton(); } private MyStaticHungrySingleton(){} public MyStaticHungrySingleton getInstance(){ return myStaticHungrySingleton; } }
public class MyHungrySingleton {
private static final MyHungrySingleton myHungrySingleton = new MyHungrySingleton();
private MyHungrySingleton(){}
private MyHungrySingleton getInstance(){
return myHungrySingleton;
}
}
懒汉式单例
优点:节省内存
缺点:性能下降
public class LazySimpleSingletion {
private static LazySimpleSingletion instance;
private LazySimpleSingletion(){}
public synchronized static LazySimpleSingletion getInstance(){
if(instance == null){
instance = new LazySimpleSingletion();
}
return instance;
}
}
//性能下降
public class LazyDoubleCheckSingletion {
private volatile static LazyDoubleCheckSingletion instance;
private LazyDoubleCheckSingletion(){}
public static LazyDoubleCheckSingletion getInstance(){
//检查是否要阻塞
if(instance==null){
synchronized (LazyDoubleCheckSingletion.class){
//检查是否要创建实例
if(instance==null){
instance = new LazyDoubleCheckSingletion();
}
}
}
return instance;
}
}
//指令重排序