java编写一个程序,实现模拟开披萨店 定义一个抽象类,Pizza,包括成员变量,名字,口味,辅料,实现构造函数,实现制作Pizza的步骤,包括准备,和面,烘烤,切片,后两个是抽象方法。 定义一个抽象类,PizzaStore,实现定披萨的方法orderPizza,传入Pizza的名字,返回Pizza,定义一个抽象方法,createPizza,在orderPizza中调用,实现不可以预定并制作不同口味的pizza。 分别定义两个Pizza的子类继承Pizza,并分别实现抽象方法 定义一个PizzaStore的子类继承PizzaStore,实现抽象方法 主类:生成两款Pizza,和一个PizzaStore店对象,实现购买Pizza
时间: 2023-08-08 11:07:55 浏览: 165
以下是Java代码实现:
抽象类Pizza:
```java
public abstract class Pizza {
private String name;
private String flavor;
private String topping;
public Pizza(String name, String flavor, String topping) {
this.name = name;
this.flavor = flavor;
this.topping = topping;
}
public void prepare() {
System.out.println("Preparing " + name);
System.out.println("Adding " + flavor + " flavor");
System.out.println("Adding " + topping + " topping");
}
public abstract void bake();
public abstract void cut();
}
```
抽象类PizzaStore:
```java
public abstract class PizzaStore {
public Pizza orderPizza(String name) {
Pizza pizza = createPizza(name);
pizza.prepare();
pizza.bake();
pizza.cut();
return pizza;
}
public abstract Pizza createPizza(String name);
}
```
Pizza子类:
```java
public class CheesePizza extends Pizza {
public CheesePizza() {
super("Cheese Pizza", "Cheese", "Tomato sauce");
}
public void bake() {
System.out.println("Baking at 350 degrees for 20 minutes");
}
public void cut() {
System.out.println("Cutting into square slices");
}
}
public class PepperoniPizza extends Pizza {
public PepperoniPizza() {
super("Pepperoni Pizza", "Pepperoni", "Mushrooms");
}
public void bake() {
System.out.println("Baking at 400 degrees for 25 minutes");
}
public void cut() {
System.out.println("Cutting into triangle slices");
}
}
```
PizzaStore子类:
```java
public class NYPizzaStore extends PizzaStore {
public Pizza createPizza(String name) {
if (name.equals("cheese")) {
return new CheesePizza();
} else if (name.equals("pepperoni")) {
return new PepperoniPizza();
} else {
return null;
}
}
}
```
主类:
```java
public class Main {
public static void main(String[] args) {
PizzaStore nyPizzaStore = new NYPizzaStore();
Pizza cheesePizza = nyPizzaStore.orderPizza("cheese");
System.out.println("Got " + cheesePizza.getName());
Pizza pepperoniPizza = nyPizzaStore.orderPizza("pepperoni");
System.out.println("Got " + pepperoniPizza.getName());
}
}
```
输出结果:
```
Preparing Cheese Pizza
Adding Cheese flavor
Adding Tomato sauce topping
Baking at 350 degrees for 20 minutes
Cutting into square slices
Got Cheese Pizza
Preparing Pepperoni Pizza
Adding Pepperoni flavor
Adding Mushrooms topping
Baking at 400 degrees for 25 minutes
Cutting into triangle slices
Got Pepperoni Pizza
```
阅读全文