数据传输对象模式【其他模式】

数据传输对象模式

public class DataTransferObject {

    /**
     *  Data Transfer Object Pattern【数据传输对象模式】:
     *  将相关的数据一次性加载出来,避免客户端多次独立调用,提高传输效率。
     */
    @Test
    public void all() {
        final Resource resource = new Resource();
        final String className = "幼稚园1班";
        final Classroom classroom = Classroom.builder().id(Long.valueOf(1)).name(className).build();
        final String stuName = "zxd";
        final Student student = Student.builder().id(Long.valueOf(1)).name(stuName).classId(classroom.getId()).build();
        resource.add(student,classroom);
        final StudentDTO dto = resource.get(student.getId());
        assertEquals(stuName, dto.getStudentName());
        assertEquals(className, dto.getClassName());
    }
}

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
class Student {
    private Long id;
    private String name;
    private Long classId;
}

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
class Classroom {
    private Long id;
    private String name;
}

// 值对象
@Value(staticConstructor = "of")
class StudentDTO {
    private String studentName;
    private String className;
}

// 模拟服务器
class Resource {
    // 模拟数据库
    private final Map<Long, Student> students = Maps.newHashMap();
    private final Map<Long, Classroom> classrooms = Maps.newHashMap();

    public void add(Student student, Classroom classroom) {
        students.put(student.getId(), student);
        classrooms.putIfAbsent(classroom.getId(), classroom);
    }

    public StudentDTO get(Long id) {
        Student stu;
        if (Optional.ofNullable(stu = students.get(id)).isPresent()) {
            final String studentName = stu.getName();
            final String className = classrooms.get(stu.getClassId()).getName();
            return StudentDTO.of(studentName, className);
        }

        return null;
    }
}

posted on 2019-01-02 20:27  竺旭东  阅读(105)  评论(0编辑  收藏  举报

导航