设计模式建造者模式
熊大
上文
工厂模式说到公司的演变过程其实就是工厂模式的演变大体其实类似。
那我们知道在相亲之前男方会把基本条件给到女方,女方看后才选择是否见面
那么我们女方感兴趣的条件列出来大致如下:
1、房 2、车 3、年收入 4、身高 5、体重 6、工作 7、血型 8、星座
转换成代码如下:
public class Man {
public Man(String house, String car,
BigDecimal yearIncome, String work) {
this.house = house;
this.car = car;
this.yearIncome = yearIncome;
this.work = work;
}
private String house;
private String car;
private BigDecimal yearIncome;
private double height;
private double weight;
private String work;
private String bloodType;
private String constellation;
}
实际中大部分女生比较重视房、车、年收入、工作性质这四项所以说这四项要求是必填至于血型、星座之类的就是零食可吃可不吃。
但是不同女生对上面的要求可能是不一样的。比如有的是真爱人家只关注星座和
血型。有的则是对年收入感兴趣、有的是对小奶狗感兴趣。
那这个时候就比较难办。
每个女生要求不一样在属性里又不能做一个统一校验那会大面积误伤。
建造者模式于是诞生了。
现在拿如花姐举例:
如花姐是来寻找真爱的 房子必须是别墅、车必须是奥迪、血型必须是o型。 那我们就为如花姐构建一个属于他的男神。
public class Man {
private String house;
private String car;
private BigDecimal yearIncome;
private double height;
private double weight;
private String work;
private String bloodType;
private String constellation;
public Man(Builder blinder){
this.house=blinder.getHouse();
this.car=blinder.getCar();
this.bloodType=blinder.getBloodType();
}
public static class Builder{
private String house;
private String car;
private String bloodType;
public Man build() throws Exception {
if (!"别墅".equals(house)) {
throw new Exception("sorry house is not villa");
}
if (!"奥迪".equals(car)) {
throw new Exception("sorry car is not audi");
}
if (!"o".equals(bloodType)) {
throw new Exception("sorry bloodType is not o");
}
return new Man(this);
}
public Builder setCar(String car) {
this.car = car;
return this;
}
public Builder setHouse(String house) {
this.house = house;
return this;
}
public Builder setBloodType(String bloodType) {
this.bloodType = bloodType;
n
return this;
}
public String getHouse() {
return house;
}
public String getCar() {
return car;
}
public String getBloodType() {
return bloodType;
}
}
public String getHouse() {
return house;
}
public String getCar() {
return car;
}
public BigDecimal getYearIncome() {
return yearIncome;
}
public double getHeight() {
return height;
}
public double getWeight() {
return weight;
}
public String getWork() {
return work;
}nam
public String getBloodType() {
return bloodType;
}
public String getConstellation() {
return constellation;
}
}
如花姐的男神正式出厂使用方法如下:
public static void main(String[] args) throws Exception {
Man build = new Man.Builder().setBloodType("o")
.setCar("奥迪")
.setHouse("别墅").build();
System.out.println(build.getCar());
System.out.println(build.getHouse());
System.out.println(build.getBloodType());
}
建造者代码还是比较简单的它其实是针对到类里面的属性:
但是其实是有一些属性是重复的。
在板砖的过程中不要过度设计合适就好(说给我自己)嘿嘿。
最后再把微信亮出来大家共同进步讨论: