设计模式--单例模式

实验7:单例模式

本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:

1、理解单例模式的动机,掌握该模式的结构;

2、能够利用单列模式解决实际问题。

[实验任务]:学号的单一

仿照课堂的身份证的例子,实现每个同学仅有一个学号这一问题。

类图

源代码

java 复制代码
public class StuID
{
    // 单例模式中的实例
    private static StuID instance = null;
    // 学号
    private String id;

    private StuID()
    {
        //私有构造函数,确保只能通过getInstance()获取实例
    }

    public static StuID getInstance()
    {
        if (instance == null)
        {
            System.out.println("第一次办理校园卡,分配新学号");
            // 创建新的实例
            instance = new StuID();
            // 设置学号
            instance.setID("20213971");
        } else
        {
            System.out.println("重复办理校园卡,获取旧学号");
        }
        return instance;
    }

    //设置学号
    private void setID(String id)
    {
        this.id = id;
    }

    //获取学号
    public String getID()
    {
        return this.id;
    }
}

public class Client
{
    public static void main(String[] args)
    {
        // 声明两个学号对象引用变量
        StuID id1, id2;
        // 获取第一个学号对象
        id1 = StuID.getInstance();
        // 获取第二个学号对象
        id2 = StuID.getInstance();
        // 检查两个学号对象是否相同
        System.out.println("学号是否一致: " + (id1 == id2));

        // 声明两个学号值变量
        String str1, str2;
        // 获取学号的值
        str1 = id1.getID();
        str2 = id2.getID();

        System.out.println("第一次学号: " + str1);
        System.out.println("第二次学号: " + str2);
        System.out.println("内容是否相等: " + (str1.equalsIgnoreCase(str2)));
        System.out.println("是否是相同对象: " + (str1 == str2));
    }
}

运行效果

相关推荐
庞轩px7 小时前
第六篇:Spring用了哪些设计模式?——从单例到代理,拆解框架中的经典设计
java·spring·设计模式·bean·代理模式·aop·单例
多加点辣也没关系8 小时前
设计模式-工厂方法模式
设计模式·工厂方法模式
多加点辣也没关系12 小时前
设计模式-建造者模式
设计模式·建造者模式
多加点辣也没关系13 小时前
设计模式-桥接模式
设计模式·桥接模式
雪度娃娃15 小时前
结构型设计模式——装饰模式
设计模式·装饰器模式
sensen_kiss15 小时前
CPT304 SoftwareEngineeringII 软件工程 2 Pt.4 设计模式(下)
设计模式·软件工程
2301_8152795215 小时前
实战分享实现 C++ 管理类单例模式:特点与最佳实践
javascript·c++·单例模式
多加点辣也没关系16 小时前
设计模式-适配器模式
设计模式
阿维的博客日记17 小时前
细说DCL单例模式和volatile有什么关系,volatile在DCL中是必要的吗??
单例模式·synchronized·happens-before
Forget the Dream17 小时前
基于适配器模式的 Axios 封装实践
设计模式·typescript·axios·适配器模式