欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Create Mode -- Builder mode

程序员文章站 2022-05-19 13:38:19
...

1 建造者模式

Create Mode -- Builder mode


interface Packing{
    public String pack();
}
class Wrapper implements Packing{
    @Override
    public String pack() {
        return "Wrapper";
    }
}
class Bottle implements Packing{
    @Override
    public String pack() {
        return "Bottle";
    }
}
interface Item{
    public String name();
    public Packing pack();
    public float price();
}
abstract class Hambur implements Item{
    @Override
    public Packing pack() {
        return new Wrapper();
    }
    @Override
    public abstract float price();
}
abstract class Colddrink implements Item{
    @Override
    public Packing pack() {
        return new Bottle();
    }
    @Override
    public abstract float price();
}
class Mcdonald extends Hambur{
    @Override
    public float price() {
        return 1000.0f;
    }
    @Override
    public String name() {
        return "Mcdonald";
    }
}
class KFC extends Hambur{
    @Override
    public float price() {
        return 2000.0f;
    }
    @Override
    public String name() {
        return "KFC";
    }
}
class Coca extends Colddrink{
    @Override
    public float price() {
        return 100.0f;
    }
    @Override
    public String name() {
        return "Coca";
    }
}
class Pepsi extends Colddrink{
    @Override
    public float price() {
        return 200.0f;
    }
    @Override
    public String name() {
        return "Pepsi";
    }
}
class Meal{
    private List<Item> items = new ArrayList<Item>();
    public void addItem(Item item){
        items.add(item);
    }
    public float getPrice(){
        float cost = 0.0f;
        for (Item item : items){
            cost += item.price();
        }
        return cost;
    }
    public void showItem(){
        for (Item item : items){
            System.out.println(item.name() + " " + item.price() + " ");
        }
        System.out.println(getPrice());
    }
}
class MealBuilder{
    public Meal prepareKFC(){
        Meal meal = new Meal();
        meal.addItem(new KFC());
        meal.addItem(new Coca());
        return meal;
    }
    public Meal preparePepsi(){
        Meal meal = new Meal();
        meal.addItem(new Mcdonald());
        meal.addItem(new Pepsi());
        return meal;
    }
}
public class Test {
    public static void main(String[] args){
        MealBuilder mealBuilder = new MealBuilder();
        Meal meal = mealBuilder.prepareKFC();
        meal.showItem();
    }
}