Transfer Object
The Transfer Object pattern is used when an object with multiple attributes needs to be passed from client to server. A model is a simple POJO class having accessor/mutator methods and is serializable so that it can be transferred over the network. The BusinessManager retrieves data from the db and sends it to the client.
public class StudentModel {
private long id;
private String firstName;
private String lastName;
private LocalDate dob;
public StudentModel(String firstName, String lastName, LocalDate dob) {
this.firstName = firstName;
this.lastName = lastName;
this.dob = dob;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public LocalDate getDob() {
return dob;
}
public void setDob(LocalDate dob) {
this.dob = dob;
}
@Override
public int hashCode() {
// code, REQUIRED
}
@Override
public boolean equals(Object obj) {
// code, REQUIRED
}
}
public class BusinessManager {
private final Set<StudentModel> students; // in memory db
public BusinessManager() {
students = new HashSet<>();
StudentModel student = new StudentModel("Bob", "Brown", LocalDate.of(1950, 8, 20));
students.add(student);
student = new StudentModel("John", "Smith", LocalDate.of(1962, 2, 11));
students.add(student);
}
public void deleteStudent(StudentModel student) {
students.remove(student);
System.out.println("Student " + student.getFirstName() + " " +
student.getLastName() + " deleted from database.");
}
public Set<StudentModel> getAllStudents() {
return students;
}
public void updateStudent(StudentModel student) {
students.add(student);
System.out.println("Student " + student.getFirstName() + " " +
student.getLastName() + " updated.");
}
}
public class TransferObjectPattern {
public static void main(String[] args) {
BusinessManager manager = new BusinessManager();
// print students
for(StudentModel student: manager.getAllStudents()) {
System.out.println(student.getFirstName() + " " + student.getLastName() + ", DOB: " + student.getDob());
}
}
}