用内部类作为建造者的建造链路,好处是方便、快捷,可以自由选择想要赋值的参数而不用写一大堆set,也不知道能set啥。
第一种:内部类不维护变量,调用方法时直接赋值给需要建造的对象
public class Dinner{
private boolean hasCandle;
private boolean hasFlower;
private int people;
private DinnerMeat dinnerMeat;
private float price;
private Dinner(){
}
public boolean isHasCandle() {
return hasCandle;
}
public boolean isHasFlower() {
return hasFlower;
}
public int getPeople() {
return people;
}
public DinnerMeat getDinnerMeat() {
return dinnerMeat;
}
public float getPrice() {
return price;
}
public static class DinnerBuilder {
private Dinner dinner;
public DinnerBuilder(){
dinner = new Dinner();
}
public DinnerBuilder candle(){
dinner.hasCandle = true;
return this;
}
public DinnerBuilder flower(){
dinner.hasFlower = true;
return this;
}
public DinnerBuilder people(int people){
dinner.people = people;
return this;
}
public DinnerBuilder meat(DinnerMeat dinnerMeat){
dinner.dinnerMeat = dinnerMeat;
return this;
}
public Dinner build(){
return dinner;
}
}
}
class Main{
public static void main(String[] args) {
Dinner dinner = new Dinner.DinnerBuilder().flower().people(3).meat(new DinnerChicken()).build();
System.out.println(JSON.toJSONString(dinner));
}
}
输出:
{"dinnerMeat":{"name":"chicken"},"hasCandle":false,"hasFlower":true,"people":3,"price":0}
第二种:
在builder里维护一份跟dinner一样的变量,在调用方法赋值时操作的是builder的变量,最后builde时将这些值赋值给dinner。
这个建造方法自由度高,如果有必须赋默认值的对象变量,一定要在初始化时赋值。比如第一种方法,要在dinner变量初始化时赋值,以免为null。