JAVA单例模式6种写法

  1. 饿汉式单例

    //饿汉式单例类.在类初始化时实例化   
    public class Singleton {
    private Singleton() {}
    private static final Singleton single = new Singleton();
    //静态工厂方法
    public static Singleton getInstance() {
    return single;
    }
    }
  2. 懒汉式1

    public class Singleton {  
    private static Singleton instance;
    private Singleton (){}

    public static Singleton getInstance() {
    if (instance == null) {
    instance = new Singleton();
    }
    return instance;
    }
    }
  3. 懒汉式2(同步方法)

    public class Singleton {  
    private static Singleton instance;
    private Singleton (){}
    public static synchronized Singleton getInstance() {
    if (instance == null) {
    instance = new Singleton();
    }
    return instance;
    }
    }
  4. 懒加载3(双重校验锁)

    public class Singleton {  
    private static Singleton singleton;
    private Singleton (){}
    public static Singleton getSingleton() {
    if (singleton == null) {
    synchronized (Singleton.class) {
    if (singleton == null) {
    singleton = new Singleton();
    }
    }
    }
    return singleton;
    }
    }
  5. 静态内部类

    public class Singleton {  
    private static class SingletonHolder {
    private static final Singleton INSTANCE = new Singleton();
    }
    private Singleton (){}
    public static final Singleton getInstance() {
    return SingletonHolder.INSTANCE;
    }
    }
  6. 枚举形式

    public enum Singleton {  
    INSTANCE;
    //任意方法,调用时使用INSTANCE.方法名
    public void whateverMethod() {
    }
    }