zno2

33) Transfer Object pattern

类别:

 

问题:

 

方案:

 

 

示例:

 

package cn.zno;

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

public class TransferObjectPatternDemo {
    public static void main(String[] args) {
        StudentBO studentBusinessObject = new StudentBO();
        // print all students
        for (StudentVO student : studentBusinessObject.getAllStudents()) {
            System.out.println("show all: [RollNo : " + student.getRollNo() + ", Name : " + student.getName() + " ]");
        }
        // update student
        StudentVO student = studentBusinessObject.getAllStudents().get(0);
        student.setName("Michael");
        studentBusinessObject.updateStudent(student);
        // get the student
        studentBusinessObject.getStudent(0);
        System.out.println("show one: [RollNo : " + student.getRollNo() + ", Name : " + student.getName() + " ]");
    }
}

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;
    }
}

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("update one: Roll No " + student.getRollNo() + ", updated in the database");
    }
}

 

show all: [RollNo : 0, Name : Robert ]
show all: [RollNo : 1, Name : John ]
update one: Roll No 0, updated in the database
show one: [RollNo : 0, Name : Michael ]

 

应用:

 

不足:(

 

优化:)

 

posted on 2023-06-16 16:58  zno2  阅读(6)  评论(0编辑  收藏  举报

导航