画类图
具体代码实现
//StudentNo.java
package org.example.design005;
public class StudentNo {
private static StudentNo instance=null;
private StudentNo(){}
public static StudentNo getInstance() {
if(instance==null){
System.out.println("第一次注册,分配新的学号");
instance=new StudentNo();
instance.setNo("20214063");
}else{
System.out.println("重复获取,获取旧的学号");
}
return instance;
}
public static void setInstance(StudentNo instance) {
StudentNo.instance = instance;
}
public String getNo() {
return no;
}
public void setNo(String no) {
this.no = no;
}
private String no;
}
//Main.java
package org.example.design005;
public class Main {
public static void main(String[] args) {
StudentNo x,y;
x=StudentNo.getInstance();
y=StudentNo.getInstance();
System.out.println("查看学号是否一致:"+(x==y));
String a,b;
a=StudentNo.getInstance().getNo();
b=StudentNo.getInstance().getNo();
System.out.println("第一次的学号:"+a);
System.out.println("第二次的学号:"+b);
System.out.println("内容是否一致:"+(a.equals(b)));
System.out.println("对象是否相同:"+(a==b));
}
}
标签:Java,instance,--,System,StudentNo,单例,println,public,out
From: https://www.cnblogs.com/liuzijin/p/17765887.html