用建造者模式实现肯德基套餐类。Java
时间: 2024-06-04 19:12:01 浏览: 63
建造者模式简介和java代码实现
public class KFCMeal {
private String burger;
private String drink;
private String side;
public KFCMeal(String burger, String drink, String side) {
this.burger = burger;
this.drink = drink;
this.side = side;
}
public String getBurger() {
return burger;
}
public void setBurger(String burger) {
this.burger = burger;
}
public String getDrink() {
return drink;
}
public void setDrink(String drink) {
this.drink = drink;
}
public String getSide() {
return side;
}
public void setSide(String side) {
this.side = side;
}
public static class Builder {
private String burger;
private String drink;
private String side;
public Builder() {}
public Builder burger(String burger) {
this.burger = burger;
return this;
}
public Builder drink(String drink) {
this.drink = drink;
return this;
}
public Builder side(String side) {
this.side = side;
return this;
}
public KFCMeal build() {
return new KFCMeal(burger, drink, side);
}
}
}
// 使用方法
KFCMeal meal = new KFCMeal.Builder()
.burger("Big Mac")
.drink("Coke")
.side("Fries")
.build();
阅读全文