单例模式(Singleton)也叫单态模式,从字面意思可以看出就是在这程序中,只有唯一的个实例。
主要思想:
(控制创建权利)私有化构造方法
(给一个获取单一实例对象入口)写个静态方法,每次返回同一实例引用
主要由两种模式
1.饿汉式(静态常量)
在类加载的时候就会实例化
public class Singleton{
private final static Singleton singleton = new Singleton();
private Singleton(){}
public static Singleton getInstance(){
return singleton;
}
}
2.懒汉式(通过同步方法)
public class Singleton{
private static Singleton singleton;
private Singleton(){};
public static sychormnized Singleton getInstance(){
if(singleton==null){
return new Singleton();
}
return singleton;
}
}
3.双重检验(Double check) 延迟加载 效率高 线程安全
public class Singleton{
private static volatile Singleton singleton;
private Singleton(){};
public static Singleton getInstance(){
if(singleton==null){
sychormnized(Singleton.class){
if(singleton==null){
singleton = new Singleton();
}
}
}
return singleton;
}
}
4.静态内部类
public class Singleton{
private Singleton(){};
private static class SingletonHolder{
private final static Singleton singleton = new Singleton();
}
public static Singleton getInstance(){
return Singleton.singleton;
}
}
5.枚举
public enum Singleton{
INSTANCE;
public void method(){
}
}