如果类的构造器或者静态工厂中具有多个参数,设计这种类时,Builder模式就是种不错的选择,特别是当大多数参数都是可选的时候。Builder也有它的不足之处,为了创建对象必须先创建它的构造器,在某些十分注重性能的情况下,可能会有增大开销的问题。
/**
* 构造器模式,应对可变参数
* Created by luoluo on 2017/12/19.
*/
public class Coffee {
private String coffeeBean;
private String water;
private String suger;
private String milk;
private String fruit;
private String cream;
public static class Bulider {
private String coffeeBean;
private String water;
private String suger;
private String milk;
private String fruit;
private String cream;
public Bulider(String coffeeBean, String water) {
this.coffeeBean = coffeeBean;
this.water = water;
}
public Bulider suger(String suger) {
this.suger = suger;
return this;
}
public Bulider milk(String milk) {
this.milk = milk;
return this;
}
public Bulider fruit(String milk) {
this.fruit = fruit;
return this;
}
public Bulider cream(String cream) {
this.cream = cream;
return this;
}
public Coffee build() {
return new Coffee(this);
}
}
private Coffee(Bulider build) {
this.coffeeBean = build.coffeeBean;
this.water = build.water;
this.suger = build.suger;
this.milk = build.milk;
this.fruit = build.fruit;
this.cream = build.cream;
}
}
public class CoffeeBuilerDemo {
public static void main(String[] args) {
Coffee coffee = new Coffee.Bulider("咖啡豆", "水").milk("牛奶")
.cream("奶油").suger("糖").build();
}
}
网友评论