三十三、传递对象模式
传递对象模式(Transfer Object Pattern),用于客户端封装输出数据为一个对象,像服务器传输出局。
实现
创建一个客户端的业务类,一个对象数据封装类即可。
- 对象实体
StudentVO.java
“`java
package patterns.transfer;
/**
* Created by lenovo on 2016/12/12 0012.
* 传出对象类
*/
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;
}
@Override
public String toString() {
return "StudentVO{" +
"name='" + name + '\'' +
", rollNo=" + rollNo +
'}';
}
}
“`
- 业务客户端类
StudentBO.java
package patterns.transfer;
import java.util.ArrayList;
import java.util.List;
/**
* Created by lenovo on 2016/12/12 0012.
* 业务对象类
*/
public class StudentBO {
//列表充当数据库
List<StudentVO> studentVOS;
public StudentBO() {
studentVOS = new ArrayList<>();
StudentVO s1 = new StudentVO("jerry", 0);
StudentVO s2 = new StudentVO("tom", 1);
studentVOS.add(s1);
studentVOS.add(s2);
}
public List<StudentVO> getAllStudents() {
return studentVOS;
}
public StudentVO getStudent(int rollNo) {
return studentVOS.get(rollNo);
}
public void updateStudent(StudentVO studentVO) {
studentVOS.get(studentVO.getRollNo()).setName(studentVO.getName());
System.out.println("更新了:" + studentVOS.get(studentVO.getRollNo()));
}
}
演示
TransferObjectPatternDemo.java
package patterns.transfer;
/**
* Created by lenovo on 2016/12/12 0012.
* 演示
*/
public class TransferObjectPatternDemo {
public static void main(String[] args) {
StudentBO studentBO = new StudentBO();
//显示所有
for (StudentVO sv : studentBO.getAllStudents()) {
System.out.println(sv.toString());
}
//更新
StudentVO s1 = studentBO.getAllStudents().get(0);
s1.setName("hahaha");
studentBO.updateStudent(s1);
//获取数据
studentBO.getStudent(1);
System.out.println(studentBO.getStudent(1).toString());
}
}
输出
StudentVO{name='jerry', rollNo=0} StudentVO{name='tom', rollNo=1} 更新了:StudentVO{name='hahaha', rollNo=0} StudentVO{name='tom', rollNo=1}