設計模式之傳輸物件模式(Transfer Object Pattern)
阿新 • • 發佈:2018-12-21
傳輸物件模式(Transfer Object Pattern)用於從客戶端向伺服器一次性傳遞帶有多個屬性的資料。傳輸物件也被稱為數值物件。傳輸物件是一個具有 getter/setter 方法的簡單的 POJO 類,它是可序列化的,所以它可以通過網路傳輸。它沒有任何的行為。伺服器端的業務類通常從資料庫讀取資料,然後填充 POJO,並把它傳送到客戶端或按值傳遞它。對於客戶端,傳輸物件是隻讀的。客戶端可以建立自己的傳輸物件,並把它傳遞給伺服器,以便一次性更新資料庫中的數值。以下是這種設計模式的實體。
業務物件(Business Object) - 為傳輸物件填充資料的業務服務。
傳輸物件(Transfer Object)
客戶端(Client) - 客戶端可以傳送請求或者傳送傳輸物件到業務物件。
程式碼:
1.傳輸物件
public class StudentVO { private String name; private int rollNo; public StudentVO(String name, int rollNo) { super(); 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; } }
2.建立業務物件
public class StudentBO { List<StudentVO> students; public StudentBO() { students=new ArrayList<StudentVO>(); StudentVO student1=new StudentVO("Elizabeth",0); StudentVO student2=new StudentVO("Henry", 1); students.add(student1); students.add(student2); } public void deleteStudent(StudentVO student) { students.remove(student.getRollNo()); System.out.println("delete rollno="+student.getRollNo()+" student 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("update rollno="+student.getRollNo()+" student from database"); } }
3.測試
public class Test {
public static void main(String[] args) {
StudentBO studentBO=new StudentBO();
//顯示所有學生
List<StudentVO> list=studentBO.getAllStudents();
for (StudentVO studentVO : list) {
System.out.println("student rollno="+studentVO.getRollNo()+",name="+studentVO.getName()+";");
}
System.out.println("####################");
//更新學生資訊
StudentVO student=studentBO.getStudent(0);
student.setName("Waider");
studentBO.updateStudent(student);
List<StudentVO> list1=studentBO.getAllStudents();
for (StudentVO studentVO : list1) {
System.out.println("student rollno="+studentVO.getRollNo()+",name="+studentVO.getName()+";");
}
System.out.println("####################");
//刪除學生
studentBO.deleteStudent(student);
List<StudentVO> list2=studentBO.getAllStudents();
for (StudentVO studentVO : list2) {
System.out.println("student rollno="+studentVO.getRollNo()+",name="+studentVO.getName()+";");
}
}
}
4.測試結果
student rollno=0,name=Elizabeth;
student rollno=1,name=Henry;
####################
update rollno=0 student from database
student rollno=0,name=Waider;
student rollno=1,name=Henry;
####################
delete rollno=0 student from database
student rollno=1,name=Henry;
5.結論
物件的操作分開,業務物件就物件服務,傳輸物件就物件。
轉載於
http://www.runoob.com/design-pattern/transfer-object-pattern.html