一、任务
使用单例模式完成单一学号问题
二、类图
三、代码
1、Java
1 package tutorial7; 2 3 public class Client { 4 public static void main(String a[]) 5 { 6 IdnumberStudent no1,no2; 7 no1=IdnumberStudent.getInstance(); 8 no2=IdnumberStudent.getInstance(); 9 System.out.println("学生学号号码是否一致:" + (no1==no2)); 10 11 String str1,str2; 12 str1=no1.getIdnumberStudent(); 13 str2=no1.getIdnumberStudent(); 14 System.out.println("第一次号码:" + str1); 15 System.out.println("第二次号码:" + str2); 16 System.out.println("***************************"); 17 System.out.println("内容是否相等:" + str1.equalsIgnoreCase(str2)); 18 System.out.println("是否是相同对象:" + (str1==str2)); 19 } 20 }
1 package tutorial7; 2 3 public class IdnumberStudent { 4 private static IdnumberStudent instance=null; 5 private String no; 6 7 private IdnumberStudent() 8 { 9 } 10 11 public static IdnumberStudent getInstance() 12 { 13 if(instance==null) 14 { 15 System.out.println("新生入学,分配学生学号!"); 16 System.out.println("***************************"); 17 instance=new IdnumberStudent(); 18 instance.setIdnumberStudent("20195589"); 19 } 20 else 21 { 22 System.out.println("重复分配学号,获取旧号码!"); 23 System.out.println("***************************"); 24 } 25 return instance; 26 } 27 28 private void setIdnumberStudent(String no) 29 { 30 this.no=no; 31 } 32 33 public String getIdnumberStudent() 34 { 35 return this.no; 36 } 37 }
2、C++
1 #include<iostream> 2 #include<string> 3 using namespace std; 4 5 class IdnumberStudent 6 { 7 private: 8 9 static IdnumberStudent* student; 10 string no; 11 IdnumberStudent() {}; 12 13 14 void setStudentNo(string no1) 15 { 16 no = no1; 17 } 18 19 public: 20 21 static IdnumberStudent* getStudent() { 22 if (student == NULL) { 23 cout << "新生入学,分配学生学号!" << endl; 24 cout << "***************************" << endl; 25 student = new IdnumberStudent(); 26 student->setStudentNo("20194023"); 27 } 28 else { 29 cout << "重复分配学号,获取旧号码!" << endl; 30 cout << "***************************" << endl; 31 } 32 return student; 33 } 34 35 string getStudentNo() { 36 return no; 37 } 38 39 }; 40 41 IdnumberStudent* IdnumberStudent::student = NULL; //初始化 student 42 43 int main() { 44 IdnumberStudent* no1, * no2; 45 no1 = IdnumberStudent::getStudent(); 46 no2 = IdnumberStudent::getStudent(); 47 if (no1 == no2) { 48 cout << "学生学号号码是否一致:true"<< endl; 49 } 50 else { 51 cout << "学生学号号码是否一致:false" << endl; 52 } 53 string str1, str2; 54 str1 = no1->getStudentNo(); 55 str2 = no2->getStudentNo(); 56 cout << "第一次号码:" + str1 << endl;; 57 cout << "第二次号码:" + str2 << endl; 58 cout << "***************************" << endl; 59 if (str1 == str2) { 60 cout << "内容是否相等:true" << endl; 61 } 62 else { 63 cout << "内容是否相等:false" << endl; 64 } 65 if (str1 == str2) { 66 cout << "是否是相同对象:true" << endl; 67 } 68 else { 69 cout << "是否是相同对象:false" << endl; 70 } 71 72 }
四、结果截图
1、Java结果截图
2、C++结果截图: