学号的单一
仿照课堂的身份证的例子,实现每个同学仅有一个学号这一问题。
类图
代码
2.1 StudentID.java package danli; public class StudentID { private static StudentID instance=null; private String ID; public String getID() { return ID; } public void setID(String iD) { ID = iD; } private StudentID() { } public static StudentID getStudentID() { if(instance==null) { instance=new StudentID(); instance.setID("20204044"); } else { System.out.println("一个学生只能有一个学号"); } return instance; } } 2.2 Client.java package danli; public class Client { public static void main(String[] args) { StudentID stu1,stu2; stu1=StudentID.getStudentID(); stu2=StudentID.getStudentID(); String str1,str2; str1=stu1.getID(); str2=stu2.getID(); System.out.println("第一次学号:"+str1); System.out.println("第二次学号:"+str2); } }
#include<iostream> using namespace std; class Student { private: string ID; static Student* instance ; Student(){} public: string getID() { return ID; } void setID(string iD) { ID = iD; } static Student* getInstance(){ if (instance==NULL){ instance = new Student(); cout << "入学分配学号" << endl; instance->setID("20204044"); } else cout << "已经入学,学号唯一" << endl; return instance; } }; Student* Student::instance=NULL; int _tmain(int argc, _TCHAR* argv[]) { Student* s, *s1; string sID, s1ID; s = Student::getInstance(); s1 = Student::getInstance(); cout << "s的学号为" << s->getID() << endl; cout << "s1的学号为" << s1->getID() << endl; cout << "s的地址为" << s << endl; cout << "s1的地址为" << s1 << endl; system("pause"); return 0; }
标签:StudentID,模式,ID,instance,static,getID,单例,public,Tutorial From: https://www.cnblogs.com/manmmm/p/16810608.html