今天做了单例模式---学号的单一的实验,并成功地运行出了结果,也知道了单例模式的优点和原理
下面是代码部分和实验要求:
[实验任务一]:学号的单一
仿照课堂的身份证的例子,实现每个同学仅有一个学号这一问题。
实验要求:
1. 画出对应的类图;
2.提交源代码;
java
1.Client
package test7;
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);
}
}
2.
package test7;
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("20194080");
}
else
{
System.out.println("一个学生只能有一个学号");
}
return instance;
}
}
C++
#include "stdafx.h"
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("20193965");
}
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;
}