设计模式系列建造者模式

编程

建造者模式使用户更加注重对象创建的过程,不需要关注创建的内部细节。

实现方式

我们平常点奶茶,可以选择大杯、中杯、小杯,什么水果,什么奶,什么茶底等

Tea对象

public class Tea {

private String teaSize;

private String milkType;

private String fruitType;

private String teaType;

public void setTeaSize(String teaSize) {

this.teaSize = teaSize;

}

public void setMilkType(String milkType) {

this.milkType = milkType;

}

public void setFruitType(String fruitType) {

this.fruitType = fruitType;

}

public void setTeaType(String teaType) {

this.teaType = teaType;

}

[@Override](https://my.oschina.net/u/1162528)

public String toString() {

return "奶茶订单{" +

"规格="" + teaSize + """ +

", 牛奶类型="" + milkType + """ +

", 水果类型="" + fruitType + """ +

", 茶底="" + teaType + """ +

"}";

}

}

TeaBuilder 构建对象

public class TeaBuilder {

private Tea tea;

public TeaBuilder() {

this.tea = new Tea();

}

public TeaBuilder addTeaSize(String teaSize) {

if (teaSize == null) {

teaSize = "中杯";

}

this.tea.setTeaSize(teaSize);

return this;

}

public TeaBuilder addMilkType(String milkType) {

if (milkType == null) {

milkType = "鲜牛奶";

}

this.tea.setMilkType(milkType);

return this;

}

public TeaBuilder addFruitType(String fruitType) {

if (fruitType == null) {

fruitType = "草莓";

}

this.tea.setFruitType(fruitType);

return this;

}

public TeaBuilder addTeaType(String teaType) {

if (teaType == null) {

teaType = "龙井";

}

this.tea.setTeaType(teaType);

return this;

}

public Tea build() {

return tea;

}

}

Test测试

public class Test {

public static void main(String[] args) {

TeaBuilder teaBuilder = new TeaBuilder();

teaBuilder.addFruitType("火龙果")

.addMilkType("酸奶")

.addTeaSize(null)

.addTeaType("红茶");

System.out.println(teaBuilder.build());

}

}

可以观察到

使用建造者模式构建对象时,只需要链式的注入属性,并不需要重复的使用set()方法。

以上是 设计模式系列建造者模式 的全部内容, 来源链接: utcz.com/z/516734.html

回到顶部