设计模式之单例模式

写在前面

本文看下单例设计模式。

写在前面

但我们看某个电影,或者是某个电视剧的时候,总会提到某某人是某某角色的原型,这里某某角色就好像是某某人的复制品一样,这里的原型设计模式也是如此,不过,这里的原型是一个对象,而原型设计模式就是指复制这个原型对象,生成一个新的对象。本文就一起来看下吧!

1:介绍

1.1:什么时候单例设计模式

当程序只需要一个对象时使用。

1.2:UML类图

原型设计模式,包含如下元素:

1:单例类
    提供一个方法获取自身唯一的实例对象。

2:实例

源码

2.1:场景

2.2:程序

  • 饿汉式
java 复制代码
//饿汉式单例
public class Hungry {
    //构造器私有,别人就无法去new这个对象,保证内存中只有一个对象
    private Hungry(){
    }
 
    private final static Hungry HUNGRY = new Hungry();
 
    public static Hungry getInstance(){
        return HUNGRY;
    }
}

可以通过反射创建新实例,非绝对安全。

  • 懒汉式(非线程安全)
java 复制代码
//懒汉式单例
public class LazyMan {
    private LazyMan() {
        System.out.println(Thread.currentThread().getName() + " ok!");
    }

    private static LazyMan lazyMan;

    public static LazyMan getInstance() {
        if (lazyMan == null) {
            lazyMan = new LazyMan();
        }
        return lazyMan;
    }
}

可以通过反射创建新实例,非绝对安全。

  • DCL懒汉式(线程安全)
java 复制代码
public class DclLazy {
    private static DclLazy instance;
    private static final Object mutexLock = new Object();

    // 私有化构造函数,防止外部创建
    private DclLazy() {}

    public static DclLazy getInstance() {
        // 第一次检查实例是否创建
        if (instance == null) {
            // 获取锁
            synchronized (mutexLock) {
                // 第二次检查实例是否创建
                if (instance == null) {
                    System.out.println("实例初始化开始了");
                    // 创建实例
                    instance = new DclLazy();
                    System.out.println("实例初始化结束了");
                }
            }
        }
        return instance;
    }
}

可以通过反射创建新实例,非绝对安全。

  • 枚举
java 复制代码
public enum EnumCls {
    zhangsan("张三女");
    private String name;

    EnumCls(String name) {
        this.name = name;
    }
}

无法通过反射创建新实例,相对安全。

写在后面

参考文章列表

单例模式(饿汉式,DCL懒汉式)

相关推荐
刷帅耍帅1 小时前
设计模式-命令模式
设计模式·命令模式
码龄3年 审核中1 小时前
设计模式、系统设计 record part03
设计模式
刷帅耍帅1 小时前
设计模式-外观模式
设计模式·外观模式
刷帅耍帅2 小时前
设计模式-迭代器模式
设计模式·迭代器模式
liu_chunhai2 小时前
设计模式(3)builder
java·开发语言·设计模式
刷帅耍帅2 小时前
设计模式-策略模式
设计模式·策略模式
刷帅耍帅7 小时前
设计模式-享元模式
设计模式·享元模式
刷帅耍帅7 小时前
设计模式-模版方法模式
设计模式
刷帅耍帅8 小时前
设计模式-桥接模式
设计模式·桥接模式
MinBadGuy9 小时前
【GeekBand】C++设计模式笔记5_Observer_观察者模式
c++·设计模式