创建一个School类对象
// 添加数据 老师们|学生们 ? 老师|学生
// 访问数据 老师们|学生们 ? 老师|学生
public class School {
private String msg;
private Collection<Teacher> teachers;
private Collection<Student> students;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
// 问题一:
// 在getter方法前,应该将teacher | students处理完毕
// 在构造School类对象时,处理teachers | students
public School() {
// 饿汉
this.teachers = new ArrayList<Teacher>();
// this.students = new ArrayList<Student>();
}
// 懒汉
private Collection<Student> exist(){
if (students == null)
return new ArrayList<Student>();
return students;
}
// 问题二:如何做到对外接口为添加 单一 老师|学生
// 答:按功能性设计setter方法
public void setTeacher(Teacher t) {
teachers.add(t);
}
public void setStudent(Student s) {
exist();
students.add(s);
}
// 问题三:如何设计getter方法
// 答:数据解析的最终目的时使用解析得到的数据,
// 如:获取第三个老师的姓名 – 该功能应该为Teacher类自身功能
// 如:获取第三个老师
// 如:获取所有老师
public Collection<Teacher> teachers(){
return teachers;
}
public Teacher geTeacher(int index) {
if (index >= teachers.size())
return null;
return ((ArrayList<Teacher>) teachers).get(index);
}
public Collection<Student> students(){
exist();
return students;
}
public Student getStudent(int index) {
exist();
if (index >= students.size())
return null;
return ((ArrayList<Student>) students).get(index);
}
@Override
public String toString() {
return "School [msg=" + msg + ", teachers=" + teachers + ", students=" + students + "]";
}
}