设计模式之-单例模式

发布时间 2023-11-28 20:00:44作者: 我也有梦想呀

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;
    }

}