软件设计:实验7:单例模式

实验7:单例模式

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

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

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

 

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

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

实验要求:

1.画出对应的类图;

2.提交源代码;

3.注意编程规范。

 

 

1.

2.import java.util.HashMap;

import java.util.Map;

 

// 学号管理类

class StudentID {

    private static Map<Integer, Boolean> idAssignments = new HashMap<>();

    private int id;

    private boolean isAssigned;

 

    public StudentID(int id) {

        this.id = id;

        this.isAssigned = false;

    }

 

    public static boolean isAssigned(int id) {

        return idAssignments.getOrDefault(id, false);

    }

 

    public static int assignNewID() {

        for (int i = 1; i <= 10000; i++) { // 假设学号范围是110000

            if (!idAssignments.containsKey(i)) {

                idAssignments.put(i, true);

                return i;

            }

        }

        return -1; // 没有可用的学号

    }

 

    public void assignID() {

        if (!isAssigned) {

            int newID = assignNewID();

            if (newID != -1) {

                this.id = newID;

                isAssigned = true;

                idAssignments.put(newID, true);

            }

        }

    }

 

    public int getId() {

        return id;

    }

 

    public boolean isAssigned() {

        return isAssigned;

    }

}

 

// 学生类

class Student {

    private int studentID;

    private String name;

    private int age;

 

    public Student(String name, int age) {

        this.name = name;

        this.age = age;

        this.studentID = 0; // 初始时学号为0,表示未分配

    }

 

    public void assignStudentID() {

        StudentID newID = new StudentID(0); // 创建一个新的学号对象

        newID.assignID(); // 分配学号

        this.studentID = newID.getId(); // 将分配的学号赋值给学生

    }

 

    public int getStudentID() {

        return studentID;

    }

 

    public String getName() {

        return name;

    }

 

    public int getAge() {

        return age;

    }

}

 

// 主类

public class UniqueStudentID {

    public static void main(String[] args) {

        Student student1 = new Student("Alice", 20);

        student1.assignStudentID(); // 分配学号

        System.out.println("Student1 ID: " + student1.getStudentID());

 

        Student student2 = new Student("Bob", 22);

        student2.assignStudentID(); // 分配学号

        System.out.println("Student2 ID: " + student2.getStudentID());

    }

}

posted @ 2024-11-27 17:02  痛苦代码源  阅读(6)  评论(0编辑  收藏  举报