设计模式之单例模式
单例模式特点:
- 单例类只能有一个实例
- 单例类必须自己创建自己的唯一实例
- 单例类必须给所有其他对象提供这一实例
单例实现的几种方式:
1. 添加同步锁保证线程安全
public class ExampleSingleton {
//volatile 禁止重排序 private volatile static ExampleSingleton exampleSingleton = null; /** * 私有化构造方法,不允许创建实例(此处忽略反射) */ private ExampleSingleton() {} /** * 方法上加同步锁,线程安全,效率太低。 * @return */ public static synchronized ExampleSingleton getInstance() { if (exampleSingleton == null) { exampleSingleton = new ExampleSingleton(); } return exampleSingleton; } /** * 双重检查锁定,线程安全 * @return */ public static ExampleSingleton getInstance() { if (exampleSingleton == null) { synchronized (ExampleSingleton.class) { if (exampleSingleton == null) { exampleSingleton = new ExampleSingleton(); } } } return exampleSingleton; } }
2. 饿汉式单例
public class ExampleSingleton { private static final ExampleSingleton exampleSingleton = new ExampleSingleton(); /** * 私有化构造方法,不允许创建实例(此处忽略反射) */ private ExampleSingleton() {} public static ExampleSingleton getInstance() { return exampleSingleton; } }
3. 静态内部类(推荐)
public class ExampleSingleton { private static class SingletonHolder { private static ExampleSingleton INSTANCE = new ExampleSingleton(); } /** * 私有化构造方法,不允许创建实例(此处忽略反射) */ private ExampleSingleton() {} public static ExampleSingleton getInstance() { return SingletonHolder.INSTANCE; } }
这种方式跟饿汉式方式采用的机制类似,但又有不同;两者都是采用了类加载的机制来保证初始化实例时只有一个线程。饿汉式是只要ExampleSingleton类被加载就会实例化,没有懒加载。静态内部类方式是在需要实例化时,调用getInstance方法,才会加载SingletonHolder类,实例化Singleton。由于类的静态属性只会在第一次加载类的时候初始化,所以在这里我们也保证了线程的安全性,所以通过这种静态内部类的方式解决了资源浪费和性能的问题。
浙公网安备 33010602011771号