设计模式(单例)

  • 作用:保证1个类只能创建1个实例,并且该类提供1个访问该实例的全局访问点
  • 优点:减少系统性能开销

饿汉式(线程安全、调用效率高、不能延时创建):

public class Singleton {
    private static Singleton instance = new Singleton();

    private Singleton() {}

    public static Singleton getInstance() {
        return instance;
    }
}

懒汉式(线程安全、调用效率低、能延时创建):

public class Singleton {
    private static Singleton instance;

    private Singleton() {}

    public static synchronized Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
}

双重校验锁(double-checked locking):

public class Singleton {
    
    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;
    }
}  

静态内部类实现方式(线程安全、调用效率高、能延时创建):

public class Singleton {
    private static class SingletonHolder {
        private static final Singleton instance = new Singleton();
    }

    private Singleton() {}

    public static Singleton getInstance() {
        return SingletonHolder.instance;
    }
}

枚举实现单例(不能延迟创建):

public enum Singleton {

    INSTANCE;

    // 添加自己需要的操作
    public void singletonOperation() {}
}

你可能感兴趣的:(设计模式(单例))