將一個複雜對象的構建與他的表示分離,使得同樣的構建過程可以創建不同的表示。 一步一步創建一個複雜的對象,它允許用戶只通過指定複雜對象的類型和內容就可以建構它們,用戶不需要知道內部的具體建構細節。
建造者模式客戶端返回的不是一個簡單的產品,而是一個由多個部件組成的複雜產品。
工廠類模式:創建單個類的模式(關注單個產品)
建造者模式:將各種產品集中起來進行管理(關注複合對象)
public interface Packing {
public String pack();
}
public interface Item {
public String name();
public Packing packing();
public float price();
}
public class Wrapper implements Packing{
@Override
public String pack() {
return "紙盒";
}
}
public class Bottle implements Packing{
@Override
public String pack() {
return "紙杯";
}
}
public abstract class Burger implements Item{
@Override
public Packing packing() {
return new Wrapper();
}
@Override
public abstract float price();
}
public abstract class ColdDrink implements Item{
@Override
public Packing packing() {
return new Bottle();
}
@Override
public abstract float price();
}
public class VegBurger extends Burger{
@Override
public String name() {
return "蔬菜漢堡";
}
@Override
public float price() {
return 30;
}
}
public class ChickenBurger extends Burger{
@Override
public String name() {
return "雞肉漢堡";
}
@Override
public float price() {
return 35;
}
}
public class Coke extends ColdDrink{
@Override
public String name() {
return "可樂";
}
@Override
public float price() {
return 30;
}
}
public class BlackTea extends ColdDrink{
@Override
public String name() {
return "紅茶";
}
@Override
public float price() {
return 25;
}
}
public class Meal {
private List<Item> items = new ArrayList<Item>();
public void addItem(Item item){
items.add(item);
}
public float getCost(){
float cost = 0;
for(Item item: items){
cost += item.price();
}
return cost;
}
public void showItem(){
for(Item item : items){
System.out.print("Item : " + item.name());
System.out.print(", Packing : " + item.packing().pack());
System.out.println(", Price : " + item.price());
}
}
}
public class MealBuilder {
public Meal prepareVegMeal (){
Meal meal = new Meal();
meal.addItem(new VegBurger());
meal.addItem(new Coke());
return meal;
}
public Meal prepareChickenMeal (){
Meal meal = new Meal();
meal.addItem(new ChickenBurger());
meal.addItem(new BlackTea());
return meal;
}
}
public static void main(String[] args) {
MealBuilder mealBuilder = new MealBuilder();
Meal vegMeal = mealBuilder.prepareVegMeal();
System.out.println("蔬菜套餐");
vegMeal.showItem();
System.out.println("價格: " + vegMeal.getCost());
Meal nonVegMeal = mealBuilder.prepareChickenMeal();
System.out.println("\n\n雞肉套餐");
nonVegMeal.showItem();
System.out.println("價格: " + nonVegMeal.getCost());
}
蔬菜套餐
Item : 蔬菜漢堡, Packing : 紙盒, Price : 30.0
Item : 可樂, Packing : 紙杯, Price : 30.0
價格: 60.0
雞肉套餐
Item : 雞肉漢堡, Packing : 紙盒, Price : 35.0
Item : 紅茶, Packing : 紙杯, Price : 25.0
價格: 60.0