传输对象模式

传输对象模式(Transfer Object Pattern)用于从客户端向服务器一次性传输多个属性的数据。传输对象也被成为数值对象。传输对象是一个具有getter/setter的简单POJO类,它是可序列化的,所以它是可以通过网路传输的,它没有任何行为。服务器端的业务类通常从数据库中读取数据,然后填充POJO,并把它发送到客户端或者按值传递它。对于客户端,传输对象是只读的,客户端可以创建自己的传输对象,并把它传递给服务器,以便一次性更行数据库中的数值,以下是这种设计模式的实体:

  • 业务对象(Bussiness Object)–> 为传输对象填充数据的业务服务
  • 传输对象(Transfer Object)–> 简单的POJO只设置getter setter方法
  • 客户端(Client) --> 客户端可以发送请求或者发送传输对象到业务对象

pojo类

package com.transfer.demo;

public class StudentVO {
	
	private String name;
	
	private Integer rollNum;
	
	public StudentVO(String name,Integer rollNum){
		this.name = name;
		this.rollNum = rollNum;
	}
	
	

	public StudentVO() {
	}



	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Integer getRollNum() {
		return rollNum;
	}

	public void setRollNum(Integer rollNum) {
		this.rollNum = rollNum;
	}
	
	

}

package com.transfer.demo;

import java.util.ArrayList;
import java.util.List;

public class StudentBO {
	
	//模拟数据库
	List studentList;
	
	public StudentBO(){
		studentList = new ArrayList<>();
		StudentVO student = new StudentVO("jack",0);
		StudentVO student2 = new StudentVO("lily",1);
		studentList.add(student);
		studentList.add(student2);
	}
	
	public void add(String name,Integer rollNum){
		StudentVO student = new StudentVO(name,rollNum);
		studentList.add(student);
		if(studentList.contains(student)){
			System.out.println("add successfully");
		}else{
			System.out.println("add failed");
		}
	}
	
	public void delete(StudentVO student){
		studentList.remove(student);
		if(!studentList.contains(student)){
			System.out.println("delete successfully");
		}else{
			System.out.println("delete failed");
		}
	}
	
	public void update(StudentVO student){
		studentList.get(studentList.indexOf(student)).setName(student.getName());
		if(studentList.get(studentList.indexOf(student)).getName().equals(student.getName())){
			System.out.println("update successfully");
		}else{
			System.out.println("update failed");
		}
	}
	
	public StudentVO getOne(Integer rollNum){
		for(StudentVO stu : studentList){
			if(stu.getRollNum() == rollNum){
				return stu;
			}
		}
		return new StudentVO();
	}
	
	public List getAll(){
		return studentList;
	}


}

package com.transfer.test;

import org.junit.Test;

import com.transfer.demo.StudentBO;
import com.transfer.demo.StudentVO;

public class DemoTest {
	
	@Test
	public void test(){
		StudentBO bo = new StudentBO();
		//获取所有
		for(StudentVO stu : bo.getAll()){
			System.out.println(stu.getName()+","+stu.getRollNum());
		}
		//增加
		bo.add("zhangsan",2);
		for(StudentVO stu : bo.getAll()){
			System.out.println(stu.getName()+","+stu.getRollNum());
		}
	}

}

你可能感兴趣的:(设计模式)