单例设计模式
- 懒汉式(消耗时间 赢得空间 不加同步会存在多线程隐患)
- 饿汉式(消耗空间 赢得时间)
- 定义final(枚举类的实现原理)
- 双重检查锁(synchronized修饰方法改为修饰代码块)
- 应用:数据库连接池,线程池。
懒汉式
public class singleton{
private singleton(){}
private static singleton uniqueInstance;
public static synchronized singleton getInstance(){
if(uniqueInstance==null)
uniqueInstance = new singleton();
return uniqueInstance;
}
}
饿汉式
public class singleton{
private singleton(){}
private static singleton uniqueInstance = new singleton();
public static singleton getInstance(){
return uniqueInstance;
}
}
定义final
public class singleton{
private singleton(){}
public static final singleton uniqueInstance = new singleton();
}
双重检查锁
public class Singleton {
private Singleton(){}
private static volatile Singleton uniqueInstance;
public static Singleton getingleton(){
if(uniqueInstance == null){
synchronized (Singleton.class){
if(uniqueInstance == null){
uniqueInstance = new Singleton();
}
}
}
return uniqueInstance;
}
}