传输对象模式(Transfer Object Pattern)

是一种业务对象传输的实践表达。

传输对象模式的实例

定义值对象类

  1. class StudentVO {
  2. constructor(name, rollNo){
  3. this.name = name;
  4. this.rollNo = rollNo;
  5. }
  6. getName() {
  7. return this.name;
  8. }
  9. setName(name) {
  10. this.name = name;
  11. }
  12. getRollNo() {
  13. return this.rollNo;
  14. }
  15. setRollNo(rollNo) {
  16. this.rollNo = rollNo;
  17. }
  18. }

定义值对象对应的业务对象

  1. class StudentBO{
  2. constructor(){
  3. //列表是当作一个数据库
  4. this.students = [];
  5. this.students.getIndexByRollNo = (rollNo)=>{
  6. return this.students.findIndex(
  7. (val)=>val.getRollNo() == rollNo
  8. );
  9. }
  10. const student1 = new StudentVO("Robert",0);
  11. const student2 = new StudentVO("John",1);
  12. this.students.push(student1);
  13. this.students.push(student2);
  14. }
  15. deleteStudent(student) {
  16. this.students.splice(student.getIndexByRollNo(student.getRollNo() ),1);
  17. console.log("Student: Roll No " + student.getRollNo()
  18. +", deleted from database");
  19. }
  20. //从数据库中检索学生名单
  21. getAllStudents() {
  22. return this.students;
  23. }
  24. getStudent(rollNo) {
  25. return this.students[this.students.getIndexByRollNo(rollNo)];
  26. }
  27. updateStudent(student) {
  28. this.students[this.students.getIndexByRollNo(student.getRollNo())].setName(student.getName());
  29. console.log("Student: Roll No " + student.getRollNo()
  30. +", updated in the database");
  31. }
  32. }

获取全部业务对象,并更新传输对象

  1. const studentBusinessObject = new StudentBO();
  2. //输出所有的学生
  3. for (const student of studentBusinessObject.getAllStudents()) {
  4. console.log("Student: [RollNo : "
  5. +student.getRollNo()+", Name : "+student.getName()+" ]");
  6. }
  7. //更新学生
  8. const student =studentBusinessObject.getAllStudents()[
  9. studentBusinessObject.getAllStudents().getIndexByRollNo(0)
  10. ];
  11. student.setName("Michael");
  12. studentBusinessObject.updateStudent(student);
  13. //获取学生
  14. studentBusinessObject.getStudent(0);
  15. console.log("Student: [RollNo : "
  16. +student.getRollNo()+", Name : "+student.getName()+" ]");

传输对象模式的优势

代码看起来和数据访问对象模式很像,但是表达的意思是完全不一样的。传输对象模式表达的是一种传输模型,数据访问对象模式表达的是模型层和操作层的分离。