设计模式学习—传输对象模式(Transfer Object Design Pattern)

来源:互联网 发布:为什么淘宝不卖太湖石 编辑:程序博客网 时间:2024/06/07 18:31

一、我的理解


该模式是作为网络中一种传输数据的方式,它利用简单的POJO对象作为传输对象,相当于一种网络传输格式的约定。

二、实现方式


业务对象负责处理数据,它只接收简单的POJO对象,然后调用其getter/setter方法获取和修改数据。

三、实例


Java实例

StudentVO类:数据对象,POJO类,只有简单的getter/setter方法

package com.study.dp.transferobject;public class StudentVO {    private String name;    private int rollNo;        public StudentVO(String name, int rollNo) {        this.name = name;        this.rollNo = rollNo;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public int getRollNo() {        return rollNo;    }    public void setRollNo(int rollNo) {        this.rollNo = rollNo;    }    }
StudentBO类:业务对象,它负责处理相应数据

package com.study.dp.transferobject;import java.util.ArrayList;import java.util.List;public class StudentBO {    // 列表是当做一个数据库    List<StudentVO> students;        public StudentBO() {        students = new ArrayList<>();        StudentVO student1 = new StudentVO("Robert", 0);        StudentVO student2 = new StudentVO("John", 1);        students.add(student1);        students.add(student2);    }        public void deleteStudent(StudentVO student) {        students.remove(student.getRollNo());        System.out.println("Student: Roll No "+student.getRollNo()+", deleted from database");    }        // 从数据库中检索出学生名单    public List<StudentVO> getAllStudents(){        return students;    }        public StudentVO getStudent(int rollNo) {        return students.get(rollNo);    }        public void updateStudent(StudentVO student) {        students.get(student.getRollNo()).setName(student.getName());        System.out.println("Student: Roll No "+student.getRollNo()+", updated in the database");    }    }
Demo类:测试类

package com.study.dp.transferobject;public class Demo {    public static void main(String[] args) {        StudentBO studentBusinessObject = new StudentBO();                // 输出所有学生        for(StudentVO student:studentBusinessObject.getAllStudents()) {            System.out.println("Student: [RollNo: "+student.getRollNo()+", Name: "+student.getName()+"]");        }                // 更新学生        StudentVO student = studentBusinessObject.getAllStudents().get(0);        student.setName("Michael");        studentBusinessObject.updateStudent(student);                // 获取学生        studentBusinessObject.getStudent(0);        System.out.println("Student: [RollNo: "+student.getRollNo()+", Name: "+student.getName()+"]");    }    }

四、应用场景



阅读全文
0 0
原创粉丝点击