单例的记录

 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,欢迎加入本校,请办理入学手续

posted @ 2019-12-23 18:31  季节风逝  阅读(220)  评论(0编辑  收藏  举报