复习:GoF的23种设计模式之Singleton模式(创建型)

Singleton模式(单例)

此模式也是我们不知不觉就会使用到的设计模式,例如我们将 配置文件映射为对象时,全局获取配置信息都使用此相同的对象。

单例模式,使用在,单例对象的类确保任何情况下都绝对只有同一个实例,整个系统都使用同一个对象。也就是 一个类只能有一个引用和一个实例方法。

单例模式在Java中有两种方式

根据单例对象的类初始化的不同分为两种构建方式:

懒汉方式,指系统启动完成后,第一次被使用时构建。

饿汉方式,指系统启动时,类装载时构建(即未被使用就已经构建)。

示例代码:

package cn.luoweiying.singleton;

public class SingletonTest {
    public static void main(String[] agrs) {
        EagerSingleton singleton = EagerSingleton.getSingleton();
        EagerSingleton singleton_two = EagerSingleton.getSingleton();
        if (singleton == singleton_two) {
            System.out.println("两个比较的对象为同一个对象");
        }
        LazySingleton lazySingleton = LazySingleton.getSingleton();
        EnumSingleton instance = EnumSingleton.INSTANCE;
        System.out.println(instance);
    }
}

class EagerSingleton {
    private static EagerSingleton singleton = new EagerSingleton();
    private EagerSingleton() {
        System.out.println("私有构造,静态代码块初始化此类");
        System.out.println("饿汉方式,指系统启动时,类装载时构建(即未被使用就已经构建)");
    }
    public static EagerSingleton getSingleton() {
        return singleton;
    }
}

class LazySingleton {
    private static LazySingleton singleton = null;
    private LazySingleton() {
        System.out.println("懒汉方式,指系统启动完成后,第一次被使用时构建");
    }
    public static LazySingleton getSingleton() {
        if (null == singleton) {
            synchronized (LazySingleton.class) {
                if (null == singleton) {
                    singleton = new LazySingleton();
                }
            }
        }
        return singleton;
    }
}

enum  EnumSingleton{
    //定义一个枚举对象,此对象就是单例对象
    INSTANCE;

    @Override
    public String toString() {
        return "枚举创建的单例对象,防止序列化与反序列化破坏单例对象";
    }
}

UML类图

 注意:序列化与反序列化会破坏单例对象

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值