Builder Pattern\(建造者模式\)

Builder Pattern(建造者模式)

目的

  1. 减少构造函数的数量, 去除参数过多的构造函数, 参数过多会引起可读性和易用性下降

例子代码

假如我们要建造个女朋友(心疼自己, 别人的女朋友不都是国家给发么, 我的怎么还需要自己 new, 国家啥时候给我发到底)

女朋友有很多属性, 年龄, 性别, (还要有性别, 心疼自己, 带不带物种呀, 删删删), 姓名等, 不同阶段我们可能知道不同的属性, 所以我们将女朋友类设计如下:

初始实现

@Getter
@Setter
public class GirlFriend {
   

    /**
     * 出生日期
     */
    private LocalDateTime birthDay;

    /**
     * 姓名
     */
    private String name;

    /**
     * 星座
     */
    private ConstellationEnum constellation;

    /**
     * 家乡
     */
    private String hometown;

    /**
     * 身高
     */
    private Integer height;

    /**
     * 体重
     */
    private Integer weight;

    /**
     * 凶兆
     */
    private CupEnum cup;

    /**
     * 刚认识, 只知道姓名
     * @param name
     */
    @BadSmell
    public GirlFriend(String name) {
   
        this.name = name;
    }

    /**
     * 开始约会聊天, 开始查户口
     * START: 你家哪的呀
     *
     * G: 内蒙古
     * I: 大草原, 骑马上学, 考试考射箭
     * G: 福建
     * I: 卖茶的
     * G: 北京
     * I: 你们那雾霾走路上看不到人吧
     * G: 四川
     * I: 你们那辣呀
     * G: 合肥
     * I: ... 合肥有啥
     * @param birthDay
     * @param name
     * @param constellation
     * @param hometown
     * @param height
     * @param weight
     */
    @BadSmell
    public GirlFriend(LocalDateTime birthDay, String name, ConstellationEnum constellation, String hometown, Integer height, Integer weight) {
   
        this.birthDay = birthDay;
        this.name = name;
        this.constellation = constellation;
        this.hometown = hometown;
        this.height = height;
        this.weight = weight;
    }

    /**
     * 开始深入聊天 ...
     * 不然呢, 你以为最后一个入参怎么知道的
     * 什么? 什么摸, 摸什么的
     * @param birthDay
     * @param name
     * @param constellation
     * @param hometown
     * @param height
     * @param weight
     * @param cup
     */
    @BadSmell
    public GirlFriend(LocalDateTime birthDay
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值