2024.11.1
设计模式实验七
软件设计 石家庄铁道大学信息学院
实验7:单例模式
本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:
1、理解单例模式的动机,掌握该模式的结构;
2、能够利用单列模式解决实际问题。
[实验任务一]:学号的单一
仿照课堂的身份证的例子,实现每个同学仅有一个学号这一问题。
实验要求:
1. 画出对应的类图;
2.提交源代码;
#include <iostream>
#include <string>
#include <stdexcept>
class Student {
private:
static Student* instance; // 静态成员,用于保存唯一实例
int id; // 学号
std::string name; // 姓名
// 私有构造函数
Student(int id, const std::string& name) : id(id), name(name) {
if (id <= 0) throw std::invalid_argument("ID must be a positive integer.");
}
public:
// 获取唯一实例
static Student* getInstance(int id, const std::string& name) {
if (instance == nullptr) {
instance = new Student(id, name);
}
return instance;
}
// 获取学号
int getId() const {
return id;
}
// 获取姓名
std::string getName() const {
return name;
}
// 设置学号(不允许修改已存在的学号)
void setId(int newId) {
if (newId <= 0) throw std::invalid_argument("ID must be a positive integer.");
id = newId; // 此处可以添加逻辑以确保学号唯一
}
// 设置姓名
void setName(const std::string& newName) {
name = newName;
}
// 打印学生信息
void printInfo() const {
std::cout << "ID: " << id << ", Name: " << name << std::endl;
}
};
// 静态成员初始化
Student* Student::instance = nullptr;
int main() {
// 创建学生对象
try {
Student* student1 = Student::getInstance(1, "Alice");
student1->printInfo();
// 尝试再次获取实例
Student* student2 = Student::getInstance(2, "Bob");
student2->printInfo(); // 这将仍然返回student1的信息
// 修改姓名
student1->setName("Alicia");
student1->printInfo();
student2->printInfo(); // student2的信息也会反映这个变化
} catch (const std::invalid_argument& e) {
std::cerr << "Error: " << e.what() << std::endl;
}
return 0;
}
3.注意编程规范。