• 面向对象包装模式的应用


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

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

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

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

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

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

    方案一示例如下:

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

    怎么样,非常简单吧。

  • 相关阅读:
    [LeetCode] Swap Nodes in Pairs
    [LeetCode] Merge k Sorted Lists
    [LeetCode] Generate Parentheses
    [LeetCode] Remove Nth Node From End of List
    [LeetCode] Longest Common Prefix
    [LeetCode] Letter Combinations of a Phone Number
    [LeetCode] Roman to Integer
    Apache shiro 笔记整理之编程式授权
    手势跟踪论文学习:Realtime and Robust Hand Tracking from Depth(三)Cost Function
    12.5 管理问题的解决方式
  • 原文地址:https://www.cnblogs.com/mkxzy/p/7091387.html
Copyright © 2020-2023  润新知