publicstatic IDCardNumber getInstance() { if (instance == null) { System.out.println("First Application for id card, get a new number."); instance = newIDCardNumber(); instance.setNumber("No10086"); } else { System.out.println("Duplicate application for id card, get the old number."); } return instance; }
publicclassClient { publicstaticvoidmain(String[] args) { IDCardNumbercard_1= IDCardNumber.getInstance(); IDCardNumbercard_2= IDCardNumber.getInstance(); System.out.println("Are the id cards the same: " + ((card_1 == card_2) ? "yes" : "no"));
Stringid_1= card_1.getNumber(); Stringid_2= card_2.getNumber(); System.out.println("The first number: " + id_1); System.out.println("The second number: " + id_2); System.out.println("Are the id numbers the same: " + ((id_1.equals(id_2)) ? "yes" : "no")); System.out.println("Are these two String objects the same: " + ((id_1 == id_2) ? "yes" : "no")); } }
运行结果为
1 2 3 4 5 6 7
First Application for id card, getanewnumber. Duplicate application for id card, getthe old number. Are the id cards the same: yes The firstnumber: No10086 The secondnumber: No10086 Are the id numbers the same: yes Are these two String objects the same: yes