首页 > 代码库 > 单例模式的两种实现方式

单例模式的两种实现方式

方式一:

public class SingletonClass {    private volatile static SingletonClass instance = null;    public static SingletonClass getInstance() {        if (instance == null) {            synchronized (SingletonClass.class) {                if (instance == null) {                    instance = new SingletonClass();                }            }        }        return instance;    }    private SingletonClass() {    }}

注意:这只是JDK1.5之后的Java的解决方案

方式二:

public class SingletonClass {    private static class SingletonClassInstance {        private static final SingletonClass instance = new SingletonClass();    }    public static SingletonClass getInstance() {        return SingletonClassInstance.instance;    }    private SingletonClass() {    }}

 

单例模式的两种实现方式