设计模式--单例模式

实验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));
    }
}

运行效果

相关推荐
basketball6164 分钟前
设计模式入门:2. 工厂模式详解 C++实现
开发语言·c++·设计模式
basketball6169 分钟前
设计模式入门:1. 单例模式详解 C++实现
c++·单例模式·设计模式
小马爱打代码10 分钟前
Spring源码中的设计模式实战:从理论到源码的深度解析
java·spring·设计模式
WiLL1 小时前
AI 时代下的 SaaS: Skill As A Service (一)
设计模式·架构
bugcome_com2 小时前
阿里云OSS工具类完整设计与实现:基于.NET的静态单例模式实践
阿里云·单例模式·.net·oss
basketball6162 小时前
设计模式入门:3. 装饰器模式详解 C++实现
c++·设计模式·装饰器模式
咖啡八杯3 小时前
GoF设计模式——装饰模式
java·算法·设计模式·装饰器模式
JAVA96511 小时前
JAVA面试-并发篇 03-使用synchronized doublecheck实现单例有什么坑
java·单例模式·面试
lqqjuly1 天前
设计模式:理论、架构与 C++ 实现—SOLID原则到23 种经典模式
c++·设计模式·架构