建造者设计模式
2020-07-26 本文已影响0人
不服输的小蜗牛
1.什么是建造者设计模式:
使用多个简单的对象一步一步构建成一个复杂的对象。
例如我们想要点一杯奶茶,里面可以添加椰果、珍珠、西米露、烧仙草、龟苓膏、芋圆、红豆,通过一个个添加最终实现我们要的奶茶
2.什么时候使用建造者设计模式:
一些基本部件不会变,而其组合经常变化的时候。简单理解就是在我们开发中一个类的参数超过四个以上,而且有些参数不是必须的。这时我们就可以使用建造者设计模式。建造者模式在开发中很常见,只要最后是以build()方法创建对象的几乎都是建造者设计模式
3建造者设计模式的优缺点:
优点:1、建造者独立,易扩展。 2、便于控制细节风险。
缺点:1、产品必须有共同点,范围有限制。 2、如内部变化复杂,会有很多的建造类。
4建造者模式的实现:
我们以奶茶为例
public class MilkTea {
private boolean coconut;
private boolean pearl;
private boolean sago;
private boolean burningGrass;
private boolean guilingPaste;
private boolean taro;
private boolean redBeans;
private MilkTea(Builder builder) {
this.coconut = builder.coconut;
this.pearl = builder.pearl;
this.sago = builder.sago;
this.burningGrass = builder.burningGrass;
this.guilingPaste = builder.guilingPaste;
this.taro = builder.taro;
this.redBeans = builder.redBeans;
}
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("您的奶茶中有");
if(coconut){
stringBuilder.append("、椰果");
}
if(pearl){
stringBuilder.append("、珍珠");
}
if(sago){
stringBuilder.append("、西米露");
}
if(burningGrass){
stringBuilder.append("、烧仙草");
}
if(guilingPaste){
stringBuilder.append("、龟苓膏");
}
if(taro){
stringBuilder.append("、芋圆");
}
if(redBeans){
stringBuilder.append("、红豆");
}
return stringBuilder.toString();
}
public static class Builder {
public boolean coconut;
public boolean pearl;
public boolean sago;
public boolean burningGrass;
public boolean guilingPaste;
public boolean taro;
public boolean redBeans;
public Builder setCoconut(boolean coconut) {
this.coconut = coconut;
return this;
}
public Builder setPearl(boolean pearl) {
this.pearl = pearl;
return this;
}
public Builder setSago(boolean sago) {
this.sago = sago;
return this;
}
public Builder setBurningGrass(boolean burningGrass) {
this.burningGrass = burningGrass;
return this;
}
public Builder setGuilingPaste(boolean guilingPaste) {
this.guilingPaste = guilingPaste;
return this;
}
public Builder setTaro(boolean taro) {
this.taro = taro;
return this;
}
public Builder setRedBeans(boolean redBeans) {
this.redBeans = redBeans;
return this;
}
public MilkTea build() {
return new MilkTea(this);
}
}
}
测试
public class Main {
public static void main(String[] args) {
MilkTea milkTea = new MilkTea.Builder()
.setBurningGrass(true)
.setCoconut(true)
.setRedBeans(true)
.build();
System.out.println(milkTea.toString());
}
输出
您的奶茶中有、椰果、烧仙草、红豆