单例模式,需要考虑的是,线程是否安全的问题。

饿汉模式单例

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

    private Singleton() { }

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

重量锁的懒汉单例模式,synchronized关键字同步

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

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

双重检查的懒汉模式单例.使用volatile关键字禁止指令重排序

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 Singleton(){}

    private static Singleton singleton;
    static {
        singleton = new Singleton();
    }

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

枚举模式单例

public class Singleton {
    private Singleton() { }

    public static Singleton getInstance() {
        return Singleton.INSTANCE.getSingleton();
    }

    private enum Singleton {
        INSTANCE;

        private Singleton singleton;

        /**JVM保证这个方法绝对只允许调用一次*/
        Singleton() {
            singleton = new Singleton();
        }

        public Singleton getSingleton() {
            return singleton;
        }
    }
}