假设肚子饿了要吃饭,吃饭要吃菜,可是做菜很麻烦,要放油、调料、肉菜等等,对于不喜欢做菜的人来说,每次都要按固定程序炒一次菜很无趣
所以我们希望一个炒菜机
public class Food
{
private final int mode;
private final String oil;
private final String seasoning;
private final boolean meat;
private final String vegetables;
// 炒菜机
public static class Builder
{
private final int mode;
private final String oil;
private String seasoning = "lajiao";
private boolean meat = false;
private String vegetables = "qingjiao";
//假设模式和放油是必须的
public Builder(int mode, String oil)
{
this.mode = mode;
this.oil = oil;
}
public Builder seasoning(String seasoning)
{
this.seasoning = seasoning;
return this;
}
public Builder meat(boolean meat)
{
this.meat = meat;
return this;
}
public Builder vegetables(String vegetables)
{
this.vegetables = vegetables;
return this;
}
public Food cook()
{
return new Food(this);
}
}
private Food(Builder builder)
{
mode = builder.mode;
oil = builder.oil;
seasoning = builder.seasoning;
meat = builder.meat;
vegetables = builder.vegetables;
System.out.println("mode: " + mode + "; oil: " + oil + "; seasoning: "
+ seasoning + "; mear: " + meat + "; vegetables: "
+ vegetables);
}
}
如此,再需要做菜的时候只需要如下调用:
{
Food.Builder builder = new Food.Builder(0, "huashengyou");
builder.seasoning("tang");
builder.meat(true);
builder.vegetables("dabaicai");
Food food = builder.cook();
}