1.定义
单例模式保证某个类在运行期间,只有一个实例对外提供服务
2.实现方式
- 构造私有化
- 创建私有静态的全局对象
- 提供一个全局访问点,供外部获取单例对象
2.1 饿汉式
public class Singleton {
private static final Singleton INSTANCE = new Singleton();
private Singleton(){}
public static Singleton getInstance(){
return INSTANCE;
}
}
2.2 懒汉式
public class Singleton {
private static Singleton INSTANCE ;
private Singleton(){}
// synchronized保证线程安全
public static synchronized Singleton getInstance(){
if (INSTANCE == null) INSTANCE = new Singleton();
return INSTANCE;
}
}
2.3 双重检查
public class Singleton {
// volatile保证变量线程可见
private volatile static Singleton INSTANCE ;
private Singleton(){}
public static Singleton getInstance(){
if (INSTANCE == null) {
synchronized (Singleton.class){
if (INSTANCE == null) INSTANCE = new Singleton();
}
}
return INSTANCE;
}
}
2.4 内部静态类
由JVM加载,由于JVM只会加载一遍,所以能保证只有1个单例
public class Singleton {
public static class SingletonHandler{
private static Singleton INSTANCE = new Singleton();
}
private Singleton(){}
public static Singleton getInstance(){
return SingletonHandler.INSTANCE;
}
}
2.5 枚举方式
最简单的实现方式,基于枚举类型的单例实现。这种实现方式通过 Java 枚
举类型本身的特性,保证了实例创建的线程安全性和实例的唯一性(同时阻
止了反射和序列化对单例的破坏)。
public enum Singleton {
INSTANCE;
public static Singleton getInstance(){
return INSTANCE;
}
}
3.总结
单例模式主要用来创建全局唯一对象。