所有示例都是用 Java 编写的
TLTR:向下滚动到 Builder 模式
装饰器模式(在这种情况下不要使用它)
如果你有一个代表矩形的类,就会使用装饰器模式。 Rectangle 类只有一种计算周长的方法。现在您想向 Rectangle 添加一个方法来计算面积。问题是您不能也不想编辑 Rectangle 类,因此您创建了一个新类 MySuperDuperRectangle,例如:
外围界面:
interface Perimeter{
public int perimeter();
}
由于某种原因我们无法更改的矩形
class Rectange implements perimeter{
private int a, b;
public Rectange(int a, int b){
this.a = a;
this.b = b;
}
public int getA(){
return a;
}
public int getB(){
return b;
}
public int perimeter(){
return 2 * a + 2 * b;
}
}
装饰的矩形:
class MySuperDuperRectange implements perimeter{
private Rectange r;
public MySuperDuperRectange(Rectange r){
this.r = r;
}
public int perimeter(){
return r.perimeter();
}
public float area(){
return r.getA() * r.getB();
}
}
Builder 模式(我会在这种情况下使用它)
我会使用 Builder 模式,因为任务是 building 披萨。
Builder 模式用于构建后缀按原样存在的东西(并且在任何时候都不应更改)。
PizzaBuiler 的基本实现如下所示:
面团枚举:
enum Dough{
WHITE, BROWN
}
奶酪枚举:
enum Cheese{
WHITE, BROWN
}
浇头枚举:
enum Topping{
Kittens, Onions, Salami
}
美味比萨:
class Pizza{
private Dough dough;
private Cheese cheese;
private HashSet<Topping> toppings;
private Pizza(Dough dough, Cheese cheese, HashSet<Topping> toppings){
this.dough = dough;
this.cheese = cheese;
this.toppings = toppings;
}
//add some getters
}
PizzaBuilder:
class PizzaBuilder{
private Dough dough;
private Cheese cheese;
private HashSet<Topping> toppings = new HashSet<Topping>();
public PizzaBuilder(){
}
public PizzaBuilder setDough(Dough dough){
this.dough = dough;
return this;
}
public PizzaBuilder setCheese(Cheese cheese){
this.cheese = cheese;
return this;
}
public PizzaBuilder addTopping(Topping topping){
this.toppings.add(topping);
return this;
}
public Pizza buildPizza(){
return new Pizza(this.dough, this.cheese, this.toppings);
}
}
现在我们要制作披萨了:
Pizza myPizza = new PizzaBuilder()
.setDough(Dough.WHITE)
.setCheese(Cheese.WHITE)
.addTopping(Topping.Kittens)
.addTopping(Topping.Salami)
.buildPizza();
正如你所见,创建一个新的比萨是非常困难的,不需要你为地球上所有可能的比萨编写一个新类;)
参考实现:Builder Pattern