单例模式
实验7:单例模式
本次实验属于模仿型实验,通过本次实验学生将掌握以下内容:
1、理解单例模式的动机,掌握该模式的结构;
2、能够利用单列模式解决实际问题。
[实验任务一]:学号的单一
仿照课堂的身份证的例子,实现每个同学仅有一个学号这一问题。
实验要求:
1. 画出对应的类图;
2. 提交源代码;
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);
}
}
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("20223875");
} else {
System.out.println("乔国峰");
}
return instance;
}
}