1 public class Student { 2 3 private static Student student = null; 4 private String name = ""; 5 6 private Student() {// 把構造方法私有化 7 8 } 9 10 public static Student getInstance() {// 定義獲取實例的方法 11 if (student == null) {// 確保只建立一個實例對象 12 student = new Student(); 13 } 14 return student; 15 } 16 17 public void setName(String name) {// 修改name成員變量的方法 18 this.name = name; 19 } 20 21 public void sayInfo() {// 輸出信息的方法 22 System.out.println(name + ",歡迎加入本校,請辦理入學手續"); 23 } 24 25 }
測試:
1 public class Test { 2 3 public static void main(String[] args) { 4 Student student1 = Student.getInstance();// 獲取實例對象 5 student1.setName("學生1"); 6 student1.sayInfo(); 7 8 Student student2 = Student.getInstance();// 獲取實例對象 9 student2.setName("學生2"); 10 student2.sayInfo(); 11 } 12 13 }
輸出結果:測試
學生1,歡迎加入本校,請辦理入學手續
學生2,歡迎加入本校,請辦理入學手續this