软件设计-单例模式
学号的单一
仿照课堂的身份证的例子,实现每个同学仅有一个学号这一问题。
类图
java
package rjsj.no7; public class StudentID { private static StudentID instance = null; private String id; private StudentID(){} public static StudentID getInstance() { if (instance == null) { System.out.println("学生信息注册,分配学号!"); instance = new StudentID(); instance.setStudentID("20193288"); } else { System.out.println("学生信息已经被注册,获取其已经存在的学号!"); } return instance; } private void setStudentID(String id) { this.id = id; } public String getStudentID() { return this.id; } }
package rjsj.no7; public class Client { public static void main(String a[]) { StudentID stu1,stu2; String id1,id2; System.out.println("第一次生成学生"); stu1 = StudentID.getInstance(); System.out.println("第二次生成学生"); stu2 = StudentID.getInstance(); System.out.println("两学生学号是否一致:" + (stu1==stu2)); id1 = stu1.getStudentID(); id2 = stu1.getStudentID(); System.out.println("第一次产生的学号:" + id1); System.out.println("第二次产生的学号:" + id2); System.out.println("内容是否相等:" + id1.equalsIgnoreCase(id2)); System.out.println("是否是相同对象:" + (id1==id2)); } }
C++
#include <iostream> using namespace std; class S_num{ private: static S_num sno; static int num; public: static S_num getintance() { // TODO Auto-generated method stub if(num==0) { cout<<"第一次办理学生证,分配新号码!"<<endl; sno.setNum(20193288); } else { cout<<"重复办理学生证,获取旧号码!"<<endl; } return sno; } int getNum() { return num; } void setNum(int n) { num = n; } }; int S_num::num = 0; S_num S_num::sno = S_num(); int main() { S_num sno1=S_num().getintance(); cout<<"第一次获取学号"<<sno1.getNum()<<endl; S_num sno2=S_num().getintance(); cout<<"第二次获取学号"<<sno2.getNum()<<endl; cout<<"内容是否相等:"<<(sno1.getNum()==sno2.getNum())<<endl; //cout<<"是否是相同对象:"<<(sno1==sno2)<<endl; }
运行截图