软件设计七
代码:#include <iostream>
#include <string>
#include <mutex>
// StudentIdGenerator class
class StudentIdGenerator {
private:
static StudentIdGenerator* instance;
static std::mutex mtx;
std::string lastGeneratedId;
int counter; // 用于生成唯一的学号(示例中简单递增)
// Private constructor to prevent instantiation
StudentIdGenerator() : counter(0) {
lastGeneratedId = "000001"; // 假设第一个学号是000001
}
public:
// Static method to return the unique instance
static StudentIdGenerator* getInstance() {
std::lock_guard<std::mutex> lock(mtx);
if (instance == nullptr) {
instance = new StudentIdGenerator();
}
return instance;
}
// Method to generate the next unique student ID
std::string generateNextId() {
std::lock_guard<std::mutex> lock(mtx);
std::string newId = lastGeneratedId;
// 这里简单地通过递增数字来生成新的学号(实际应用中可能更复杂)
counter++;
std::ostringstream oss;
oss << std::setfill('0') << std::setw(6) << counter + 1;
lastGeneratedId = oss.str();
return newId;
}
};
// Static member initialization
StudentIdGenerator* StudentIdGenerator::instance = nullptr;
std::mutex StudentIdGenerator::mtx;
// Student class
class Student {
private:
std::string studentId;
public:
// Constructor that takes a StudentIdGenerator to get a unique ID
Student(StudentIdGenerator& idGenerator) {
studentId = idGenerator.generateNextId();
}
// Method to get the student ID
std::string getStudentId() const {
return studentId;
}
};
int main() {
// Get the unique instance of the StudentIdGenerator
StudentIdGenerator* idGenerator = StudentIdGenerator::getInstance();
// Create students and print their IDs
Student student1(*idGenerator);
Student student2(*idGenerator);
std::cout << "Student 1 ID: " << student1.getStudentId() << std::endl;
std::cout << "Student 2 ID: " << student2.getStudentId() << std::endl;
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 张高兴的大模型开发实战:(一)使用 Selenium 进行网页爬虫
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构