Java学习之数据封装与引用对象的应用
偶然间发现了一种数据封装的新思想,记录一下:
简单说明一下:People是数据集合,Teacher和Student是People的属性,然后新建对象不是简简单单的new一个对象,而是通过“handler”灵活创建对象,更重要的可以根据实际情景进行业务处理。
Bean:
public class People { private int id; private Student student; private Teacher teacher; public People() { } public void setId(int id) { this.id = id; } public void setStudent(Student student) { this.student = student; } public void setTeacher(Teacher teacher) { this.teacher = teacher; } public int getId() { return id; } public Student getStudent() { return student; } public Teacher getTeacher() { return teacher; } @Override public String toString() { return "People{" + "id=" + id + ", student=" + student + ", teacher=" + teacher + '}'; } }
public class Teacher { private int id; private String name; public Teacher(int id, String name) { this.id = id; this.name = name; } public void setId(int id) { this.id = id; } public void setName(String name) { this.name = name; } public int getId() { return id; } public String getName() { return name; } @Override public String toString() { return "Teacher{" + "id=" + id + ", name='" + name + '\'' + '}'; } }
public class Student { private int id; private String name; public Student(int id, String name) { this.id = id; this.name = name; } public void setId(int id) { this.id = id; } public void setName(String name) { this.name = name; } public int getId() { return id; } public String getName() { return name; } @Override public String toString() { return "Student{" + "id=" + id + ", name='" + name + '\'' + '}'; } }
接口:
public interface HandlerInterface { public void getObject(People people); }
实现类:
public class TeacherHandler implements HandlerInterface { @Override public void getObject(People people) { Teacher teacher = selectById(people.getId()); people.setTeacher(teacher); } //随便赋值模仿数据库查询 private Teacher selectById(int id) { return new Teacher(id, "teacher"); } }
public class StudentHandler implements HandlerInterface { @Override public void getObject(People people) { Student student = selectById(people.getId()); people.setStudent(student); } //随便赋值模仿数据库查询 private Student selectById(int id) { return new Student(id, "student"); } }
工具类:
public class Handler { private static List<HandlerInterface> handlerList = new ArrayList<>(4); static { initHandler(); } private static void initHandler() { handlerList.add(new TeacherHandler()); handlerList.add(new StudentHandler()); } public static List<HandlerInterface> getHandler() { return handlerList; } }
测试:
public class Test { public static void main(String[] args) { People people = new People(); people.setId(1); List<HandlerInterface> handlerList = Handler.getHandler(); for (HandlerInterface handler : handlerList) { handler.getObject(people); } System.out.println(people); } }