建造者模式:将一个复杂的构建与其表示相分离,使得同样的构建过程可以创建不同的表示。
优点: 1、建造者独立,易扩展。 2、便于控制细节风险。
缺点: 1、产品必须有共同点,范围有限制。 2、如内部变化复杂,会有很多的建造类。
使用场景: 1、需要生成的对象具有复杂的内部结构。 2、需要生成的对象内部属性本身相互依赖。
建造者模式与工厂模式的区别?
建造者模式是让建造者类来负责对象的创建工作;工厂模式是由工厂类来负责对象创建的工作。
工厂模式是用来创建不同但是相关类型的对象(继承同一父类或者接口的一组子类),由给定的参数来决定创建哪种类型的对象。建造者模式是用来创建一种类型的复杂对象,通过设置不同的可选参数,“定制化”地创建不同的对象。建造者模式更加关注与建造零件装配的顺序(过程)。
拿披萨汉堡举例,顾客走进一家餐馆点餐,我们利用工厂模式,根据用户不同的选择,来制作不同的食物,比如披萨、汉堡等。对于披萨来说,用户又有各种配料可以定制,such as cheese, sauce,meet,vegatables etc,通过建造者模式根据用户选择的不同配料来制作披萨。
Take pizza for example,show you my code:
public class PizzaDirector {
public static void main(String[] args) {
PizzaBuilder veggieBuilder = new VeggieLoversPizzaBuilder();
Pizza veggie = veggieBuilder.addSauce().addCheese().addOlives().addTomatoes().addSausage().build()
.prepare().bake().cut().box();
PizzaBuilder meatBuilder = new MeatLoversPizzaBuilder();
Pizza meat = meatBuilder.addSauce().addTomatoes().addCheese().addSausage().addPepperoni().build()
.prepare().bake().cut().box();
}
}
public abstract class PizzaBuilder {
String name;
List<String> toppings = new ArrayList<String>();
public abstract PizzaBuilder addCheese();
public abstract PizzaBuilder addSauce();
public abstract PizzaBuilder addTomatoes();
public abstract PizzaBuilder addGarlic();
public abstract PizzaBuilder addOlives();
public abstract PizzaBuilder addSpinach();
public abstract PizzaBuilder addPepperoni();
public abstract PizzaBuilder addSausage();
public Pizza build() {
Pizza pizza = new Pizza();
pizza.setName(this.name);
pizza.addToppings(toppings);
return pizza;
}
}
public class VeggieLoversPizzaBuilder extends PizzaBuilder {
public VeggieLoversPizzaBuilder() {
this.name = "Veggie Lovers Pizza";
}
public PizzaBuilder addCheese() {
this.toppings.add("parmesan");
return this;
}
public PizzaBuilder addSauce() {
this.toppings.add("sauce");
return this;
}
public PizzaBuilder addTomatoes() {
this.toppings.add("chopped tomatoes");
return this;
}
public PizzaBuilder addGarlic() {
this.toppings.add("garlic");
return this;
}
public PizzaBuilder addOlives() {
this.toppings.add("green olives");
return this;
}
public PizzaBuilder addSpinach() {
this.toppings.add("spinach");
return this;
}
public PizzaBuilder addPepperoni() {
return this;
}
public PizzaBuilder addSausage() {
return this;
}
}
public class MeatLoversPizzaBuilder extends PizzaBuilder {
public MeatLoversPizzaBuilder() {
this.name = "Meat Lovers Pizza";
}
public PizzaBuilder addCheese() {
this.toppings.add("mozzerella");
return this;
}
public PizzaBuilder addSauce() {
this.toppings.add("NY style sauce");
return this;
}
public PizzaBuilder addTomatoes() {
this.toppings.add("sliced tomatoes");
return this;
}
public PizzaBuilder addGarlic() {
this.toppings.add("garlic");
return this;
}
public PizzaBuilder addOlives() {
return this;
}
public PizzaBuilder addSpinach() {
return this;
}
public PizzaBuilder addPepperoni() {
this.toppings.add("pepperoni");
return this;
}
public PizzaBuilder addSausage() {
this.toppings.add("sausage");
return this;
}
}