本人为菜鸟,仅供参考,只为自己记录学习
使用情况
基础类别不变,而其组合经常改变
优点
建造者独立,易扩展、便于控制细节风险
与工厂模式区别
建造者模式更加关注与零件装配的顺序
食物接口
public interface Food {
/**
* 食品名称
* @return
*/
public String name();
/**
* 食品包装
* @return
*/
public Packing packing();
/**
* 价格
* @return
*/
public float price();
}
食物抽象类
汉堡抽象类
public abstract class Burger implements Food {
/**
* 汉堡的包装
*/
@Override
public Packing packing() {
return new Wrapper();
}
/**
* 汉堡的价格
* @return
*/
@Override
public abstract float price();
}
饮品抽象类
public abstract class Drink implements Food {
/**
* 饮料的包装
* @return
*/
@Override
public Packing packing() {
return new Bottle();
}
/**
* 饮料的价格
* @return
*/
@Override
public abstract float price();
}
包装接口类
public interface Packing {
/**
* 包装
* @return
*/
public String pack();
}
包装实现类
瓶子包装
public class Bottle implements Packing {
@Override
public String pack() {
return "bottle";
}
}
纸质包装
public class Wrapper implements Packing {
@Override
public String pack() {
return "wrapper";
}
}
订单实现类
public class Order {
private List<Food> foods = new ArrayList<>();
private float price;
public void addFood(Food food) {
foods.add(food);
price += food.price();
}
public float getPrice() {
return price;
}
public String showOrder() {
StringBuilder sb = new StringBuilder();
for (Food food : foods) {
sb.append(food.name()).append(" : ").append(food.price()).append(" ");
}
sb.append("total price : ").append(price);
return sb.toString();
}
}
订单套餐构建类
public class OrderBuilder {
// 素食汉堡套餐
public Order getVegMeal() {
Order order = new Order();
order.addFood(new VegBurger());
order.addFood(new Coke());
return order;
}
// 鸡肉汉堡套餐
public Order getChickenMeal() {
Order order = new Order();
order.addFood(new ChickenBurger());
order.addFood(new Pepsi());
return order;
}
//这里可以与工厂模式共同实现一个任意点餐的一个接口
}
测试类
public class BuilderTest {
public static void main(String[] args) {
OrderBuilder builder = new OrderBuilder();
Order vegMeal = builder.getVegMeal();
System.out.println(vegMeal.showOrder());
}
}