當我們想要在客戶端到服務器的一個傳遞具有多個屬性的數(shù)據(jù)時,可使用傳輸對象模式。傳輸對象也稱為值對象。傳輸對象是一個具有g(shù)etter/setter方法的簡單POJO類,并且是可序列化的,因此可以通過網(wǎng)絡傳輸。 它沒有任何行為。服務器端業(yè)務類通常從數(shù)據(jù)庫獲取數(shù)據(jù)并填充到POJO類,并將其發(fā)送到客戶端或通過值傳遞它。對于客戶端,傳輸對象是只讀的。 客戶端可以創(chuàng)建自己的傳輸對象,并將其傳遞給服務器,以便一次性更新數(shù)據(jù)庫中的值。 以下是這種類型的設(shè)計模式的實體。
在這個實現(xiàn)實例中,將創(chuàng)建一個StudentBO作為業(yè)務對象,Student作為傳輸對象表示實體。
TransferObjectPatternDemo是一個演示類,在這里充當客戶端,將使用StudentBO和Student演示傳輸對象設(shè)計模式。
服務定位器模式示例的結(jié)構(gòu)如下圖所示 -
創(chuàng)建一個傳輸對象,其代碼如下所示 -
StudentVO.java
public class StudentVO { private String name; private int rollNo; 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; } }
創(chuàng)建一個業(yè)務對象,其代碼如下所示 -
StudentBO.java
import java.util.ArrayList; import java.util.List; public class StudentBO { //list is working as a database List<StudentVO> students; public StudentBO(){ students = new ArrayList<StudentVO>(); 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"); } //retrive list of students from the 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"); } }
使用StudentBO演示傳輸對象設(shè)計模式,其代碼如下所示 -
TransferObjectPatternDemo.java
public class TransferObjectPatternDemo { public static void main(String[] args) { StudentBO studentBusinessObject = new StudentBO(); //print all students for (StudentVO student : studentBusinessObject.getAllStudents()) { System.out.println("Student: [RollNo : " + student.getRollNo() + ", Name : " + student.getName() + " ]"); } //update student StudentVO student = studentBusinessObject.getAllStudents().get(0); student.setName("Michael"); studentBusinessObject.updateStudent(student); //get the student student = studentBusinessObject.getStudent(0); System.out.println("Student: [RollNo : " + student.getRollNo() + ", Name : " + student.getName() + " ]"); } }
驗證輸出,執(zhí)行上面的代碼得到以下結(jié)果 -
Student: [RollNo : 0, Name : Robert ] Student: [RollNo : 1, Name : John ] Student: Roll No 0, updated in the database Student: [RollNo : 0, Name : Michael ]