zoukankan      html  css  js  c++  java
  • 面向对象包装模式的应用

    在开发过程中,会遇到很多奇怪的需求

    比如各种各样的通知类型。

    每种类型的数据结构各不相同

    但是需要统一返回给前端显示

    最直接的解决方案是增加一个“超级”类,把所有包含的属性都加到这个类中

    这个方案的优势是简单,缺点是没有扩展性,每增加一种新的类型都要修改

    方案一示例如下:

    @Data
    public class ServiceMessage {

    @Id
     private String id;

    /**报名导游id**/
     private Integer userId;

    /**旅行社名称**/
     @JsonInclude(JsonInclude.Include.NON_NULL)
    private String agent;

    /**线路标题**/
     @JsonInclude(JsonInclude.Include.NON_NULL)
    private String title;

    /**开始带团时间**/
     @JsonInclude(JsonInclude.Include.NON_NULL)
    @JsonFormat(shape = JsonFormat.Shape.STRING)
    private LocalDateTime startTime;

    /**结束带团时间**/
     @JsonInclude(JsonInclude.Include.NON_NULL)
    @JsonFormat(shape = JsonFormat.Shape.STRING)
    private LocalDateTime endTime;

    /**导游类型**/
     @JsonInclude(JsonInclude.Include.NON_NULL)
    private Integer guideType;

    // 派团ID
     @JsonInclude(JsonInclude.Include.NON_NULL)
    private String delegationId;

    // 价格
     @JsonInclude(JsonInclude.Include.NON_NULL)
    private Integer price;

    // 通知类型
     private String noticeType;

    @JsonFormat(shape = JsonFormat.Shape.STRING)
    private LocalDateTime createTime;

    /**
    * 短信内容
     */
     @JsonInclude(JsonInclude.Include.NON_NULL)
    private String content;

    /**
    * 导游认证类型,1身份认证成功 2身份认证失败 3导游认证成功 4导游认证失败
     */
     @JsonInclude(JsonInclude.Include.NON_NULL)
    private Integer authType;

    // 失败原因
     @JsonInclude(JsonInclude.Include.NON_NULL)
    private String remark;
    }

    另外一个方案是利用包装模式(我自己的命名)

    新建一个新的类来包装实际对象,并用一个根类Object访问,这样便达到了扩展的目的。在面向对象的语言里也很容易实现

    这个方案的优势是扩展性非常好,几乎支持任意数据结构。

    这个方案的缺点是多了一次包装,访问的时候不够直观。

    由于非结构化特性,这种模式适合用NoSQL数据库进行存储,比如MongoDB

    方案二示例如下:

    @Data
    public class CustomerDto {

    // private String id;
      private String type;
    private Object refObj;
    private String letterIndex;
    // private String name;
    // private String phone;
    // private Integer gender;
    // private String description;
    // private String letterIndex;
    // private String remark;
    }

    怎么样,非常简单吧。

  • 相关阅读:
    ContextLoaderListener作用详解
    @Autowired与@Resource的区别
    使用SimpleDateFormat时的日期和时间模式
    git将本地内容传送到远程仓库出现![rejected] master -> master (fetch first)错误
    使用SSH框架遇到的错误总结
    struts2 action中字符串转json对象出错 java.lang.NoClassDefFoundError: org/apache/commons/lang/exception/NestableRuntimeException
    2017百度web前端实习生在线笔试题
    学习模型-视图-控制器MVC模式
    DOM元素加载之前执行的jQuery代码
    使用$.post和action或servlet交互 URL出现 http://localhost:8080/../[object%20Object] 错误的问题解决
  • 原文地址:https://www.cnblogs.com/mkxzy/p/7091387.html
Copyright © 2011-2022 走看看