代码实现

披萨店

public abstract class PizzaStore{
    public Pizza orderPizza(String type){
        Pizza piaaa;
        pizza = createPizza(type);
        pizza.prepare();
        pizza.bake();
        pizza.cut();
        pizza.box();
        return pizza;
    }
    abstract Pizza createPizza(String type);
}

开一家披萨店把

public class NYPizzaStore extends PizzaStore{
//createPizza()返回一个Pizza对象,由子类全权负责实例化哪一个具体Pizza
    Pizza createPizza(String item){
        if(item.equals("cheese")){
        //创建具体类
            return new NYStyleCheesePizza();
        }else if(item.equals("veggie")){
            return new NYStyleVeggiePizza();
        }else if(item.equals("clam")){
            return new NYStyleClamPizza();
        }else if(item.equals("pepproni")){
            return new NYStylePepproni();
        }else return null;
    }
}

纽约风味的具体子类

public class NYStyleCheesePizza extends Pizza{
    public NYStyleCheesePizza(){
        name = "NY Style Sauce and Cheese Pizza";
        dough = "Thin Crust Dough";
        sauce = "Marinara Sauce";

        toppings.add("Grated Reggiano Cheese");
    }
}

有了披萨店,该生产披萨了

public abstract class Pizza{
    String name;
    String dough;
    String sauce;
    ArrayList toppings = new ArrayList();

    void prepare(){
        System.out.println("Preparing" + name);
        System.out.println("Tossing dough");
        System.out.println("Adding sauce");
        System.out.println("Adding toppings: ");
        for(int i=0; i"  " + topping.get(i));
        }
    }

    void bake(){
        System.out.println("Bake for 25 minutes at 350");
    }

    void cut(){
        System.out.println("Cutting the pizza into diagonal slices");
    }

    void box(){
        System.out.println("Place pizza in official PizzaStore box");
    }

    public String getName(){
        return name;
    }
}

现在可以吃披萨了

public class PizzaTestDrive{
    public static void main(String[] args){
        PizzaStore nyStore = new NYPizzaStore();

    Pizza pizza = nyStore.orderPizza("cheese");
    System.out.println("Ethan ordered a "+ pizza.getName() + "\n");
    }
}

你可能感兴趣的:(代码实现)