设计模式之-单例模式

1、是什么?

单例模式是一种常用的软件设计模式,它在一个类中只允许创建一个对象实例,并且提供一个全局访问点来访问该实例。

2、怎么玩?

单例模式需要满足三个条件:单例类只能有一个实例;单例类必须自己创建自己的唯一实例;单例类必须给所有其他对象提供这一实例。

(1) 懒汉式
package com.ly.singleton;

/**
 * 单例模式-懒汉式
 *
 * @author ly (个人博客:https://www.cnblogs.com/ybbit)
 * @date 2023-10-31  0:00
 * @tags 喜欢就去努力的争取
 */
public class Person {
    private String name;
    private Integer age;

    public static Person instance;

    private Person() {
    }

    /**
     * 在需要的时候再去创建
     *
     * @return 实例对象
     */
    public static Person getInstance() {
        if (instance != null) {
            instance = new Person();
        }
        return instance;
    }
}
(2) 饿汉式
package com.ly.singleton;

/**
 * 单例模式-饿汉式
 *
 * @author ly (个人博客:https://www.cnblogs.com/ybbit)
 * @date 2023-10-31  0:02
 * @tags 喜欢就去努力的争取
 */
public class Person2 {

    private String name;

    private Integer age;

    /**
     * 上来就直接创建
     */
    private static final Person2 PERSON = new Person2();

    public static Person2 getInstance() {
        return PERSON;
    }
}

(3) 懒汉式的一些问题
package com.ly.singleton;

/**
 * 单例模式-懒汉式
 *
 * @author ly (个人博客:https://www.cnblogs.com/ybbit)
 * @date 2023-10-31  0:00
 * @tags 喜欢就去努力的争取
 */
public class Person3 {
    private String name;
    private Integer age;

    public static volatile Person3 instance;

    private Person3() {
    }

    /**
     * 静态方法
     * 锁太大效率太低
     *
     * @return 实例对象
     */
    public static synchronized Person3 getInstance1() {
        if (instance != null) {
            instance = new Person3();
        }
        return instance;
    }

    /**
     * 双重检索+内存可见性
     *
     * @return
     */
    public static Person3 getInstance2() {
        if (instance != null) {
            synchronized (Person3.class) {
                if (instance != null) {
                    instance = new Person3();
                }
            }
        }
        return instance;
    }

}

posted @   我也有梦想呀  阅读(9)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 张高兴的大模型开发实战:(一)使用 Selenium 进行网页爬虫
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
历史上的今天:
2022-11-28 整合SpringBoot + Dubbo + Nacos 出现 Unable to make protected final java.lang.Class java.lang.ClassLoader.defineClass
点击右上角即可分享
微信分享提示