单例设计模式:
定义:保证类在内存中只有一个对象。
步骤:
1.私有构造方法
2.创建唯一对象
3.对外仅提供访问方法
最常见的2种方法:
懒汉式与饿汉式 两者区别:
饿汉式:线程安全,空间换时间,不能延迟加载
public class SingletonHungry {
private SingletonHungry(){}
private static SingletonHungry singletonHungry = new SingletonHungry();
private static SingletonHungry getInstance(){
return singletonHungry;
}
}
懒汉式:线程不安全,时间换空间,可以延迟加载
public class SingletonLazy {
private SingletonLazy(){}
private static SingletonLazy singletonLazy;
private static synchronized SingletonLazy getInstance(){
if(singletonLazy==null){
singletonLazy = new SingletonLazy();
}
return singletonLazy;
}
}
其他方法:
1.双重检测锁式:
public class SingletonDoubleLock {
private SingletonDoubleLock(){}
private static SingletonDoubleLock instance =null;
public static SingletonDoubleLock getInstance(){
if(instance==null){
SingletonDoubleLock singletonDoubleLock;
synchronized (SingletonDoubleLock.class){
singletonDoubleLock = instance;
if(singletonDoubleLock==null){
synchronized(SingletonDoubleLock.class){
if(singletonDoubleLock==null){
singletonDoubleLock = new SingletonDoubleLock();
}
}
}
}
return singletonDoubleLock;
}
return instance;
}
}
2.静态内部类式:线程安全,调用效率高,可以延迟加载
public class SingletonStatic {
private SingletonStatic(){}
private static class SingletonClassInstance{
private static final SingletonStatic singletonStatic = new SingletonStatic();
}
public static SingletonStatic getInstance(){
return SingletonClassInstance.singletonStatic;
}
}
3.枚举式:线程安全,调用效率高,不能延迟加载
public enum SingletonEnum {
INSTANCE;
}