Builder Pattern(建造者模式)
目的
- 减少构造函数的数量, 去除参数过多的构造函数, 参数过多会引起可读性和易用性下降
例子代码
假如我们要建造个女朋友(心疼自己, 别人的女朋友不都是国家给发么, 我的怎么还需要自己 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