当前位置: 移动技术网 > IT编程>软件设计>设计模式 > 十分钟学会设计模式(一):单例模式

十分钟学会设计模式(一):单例模式

2020年07月22日  | 移动技术网IT编程  | 我要评论

单例模式(Singleton Pattern):无法直接new对象,只能通过该类提供的全局访问点直接创建或返回一个该类的唯一对象。

饿汉模式

public class HungerSingleton {

    // 实例化一个该类的对象
    private static HungerSingleton instance = new HungerSingleton();

    // 私有化构造方法,防止该类被其他类实例化
    private HungerSingleton() {}

    // 获取唯一可用对象
    public static HungerSingleton newInstance() {
        return instance;
    }
}

懒汉模式

由于饿汉模式在类加载后就会直接创建,当使用单例的类可能会很多时,会造成资源浪费,所以有了懒汉模式。

懒汉一
public class LazySingleton {

    private static LazySingleton instance;

    private LazySingleton() {}

    public static LazySingleton newInstance() {
        if (instance == null) {
            instance = new LazySingleton();
        }
        return instance;
    }
}

上面是一个简单的懒汉模式,问题是不支持多线程。

懒汉二
public class LazySingleton {

    private static LazySingleton instance;

    private LazySingleton() {}

    public static synchronized LazySingleton newInstance() {
        if (instance == null) {
            instance = new LazySingleton();
        }
        return instance;
    }
}

加上synchronized后解决了线程安全问题,但是加在方法上性能影响较大,改进如下:

public class LazySingleton {

	// 加上volatile关键字禁止指令重排序
    private static volatile LazySingleton instance;

    private LazySingleton() {}

    public static LazySingleton newInstance() {
    	// 双重检查
        if (instance == null) {
            synchronized (LazySingleton.class) {
                if (instance == null) {
                    instance = new LazySingleton();
                }
            }
        }
        return instance;
    }
}
懒汉三

基于类初始化延迟加载获取对象,也是线程安全的:

public class Singleton {

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

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

本文地址:https://blog.csdn.net/qq_25149027/article/details/107482493

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网