具体代码
//Main.java
package org.example.test006;
public class Main {
public static void main(String[] args) {
System.out.println("分配学号:");
StudentNumber s1 =new StudentNumber();
StudentNumber s2=new StudentNumber();
s1=StudentNumber.getInstance(s1,1);
s2=StudentNumber.getInstance(s2,2);
String s11,s22;
s11=s1.getStudentNumber();
s22=s2.getStudentNumber();
System.out.println("s1的学号为:"+s11);
System.out.println("s2的学号为:"+s22);
System.out.println("查看s1和s2是否为同一个学号:");
System.out.println(s1==s2);
System.out.println("尝试再次为s1分配学号:");
s1=StudentNumber.getInstance(s1,3);
System.out.println("查看s1和s2的学号是否相同:");
System.out.println(s11==s22);
}
}
//StudentNumber.java
package org.example.test006;
public class StudentNumber {
public String getStudentNumber() {
return studentNumber;
}
public void setStudentNumber(String studentNumber) {
this.studentNumber = studentNumber;
}
private String studentNumber;
StudentNumber(){}
public static StudentNumber instance=null;
public static StudentNumber getInstance(StudentNumber sn,int i){
if(sn.getStudentNumber()==null){
System.out.println("第"+i+"位学生还没有学号,分配新的学号:");
instance=new StudentNumber();
instance.setStudentNumber("20214063"+i);
}else{
System.out.println("已经有学号啦~");
}
return instance;
}
}