一、简介
文章参考 |java单例模式——详解JAVA单例模式及8种实现方式
单例模式确保一个类只会生成一个实例,可以节省内存。
二、饿汉式
优点:实现简单,线程安全
缺点:类加载的时候就完成实例化,可能会造成内存浪费
代码如下:
class Singleton {
private final static Singleton SINGLETON =new Singleton();
private Singleton(){}
public static Singleton getInstance(){
return SINGLETON;
}
}
三、懒汉式
1 原始方法
优点:需要使用实例时才会生成,节省内存
缺点:线程不安全
class Singleton {
private static Singleton SINGLETON;
private Singleton(){}
public static Singleton getInstance(){
if (SINGLETON==null){
SINGLETON=new Singleton();
}
return SINGLETON;
}
}
2 双重检查
第一个if判断是为了避免不必要的同步,synchronized加锁开销大,若已经创建了对象就可以直接返回该对象。
第2个if判断是为了避免对象重复创建。如果多个线程通过了第一次if判断,其中一个线程获得了锁创建了对象,其余线程就不会再创建对象。
class Singleton {
private static Singleton SINGLETON;
private Singleton() {
}
public static Singleton getInstance() {
if (SINGLETON == null) {
synchronized (Singleton.class) {
if (SINGLETON == null) {
SINGLETON = new Singleton();
}
}
}
return SINGLETON;
}
}
3 静态内部类
静态内部类在类加载时不会实例化,在调用getInstance方法的时候才会实例化,保证了线程安全,又节省内存
class Singleton {
private Singleton() {
}
private static class SingletonInstance{
private static final Singleton INSTANCE=new Singleton();
}
public static Singleton getInstance(){
return SingletonInstance.INSTANCE;
}
}
四 枚举类
enum Singleton {
INSTANCE;
}