zoukankan      html  css  js  c++  java
  • 数据传输对象模式【其他模式】

    数据传输对象模式

    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;
        }
    }
    
  • 相关阅读:
    PHP | 运算符优先级
    Docker配置PHP+Nginx+MySQL
    Windows下Mysql主从配置
    php-fpm重启配置修改无效
    MySQL事务
    hadoop伪集群搭建
    Springboot2.x源码下载安装
    微服务——服务之间访问,用Feign请求服务接口超时如何解决?
    Lua安装
    日期——计算每月第一天和最后一天
  • 原文地址:https://www.cnblogs.com/zhuxudong/p/10211113.html
Copyright © 2011-2022 走看看