return pizza;
}
//抽象工厂方法,让子类创建披萨实例
abstract Pizza createPizza(String type);
}
```
具体商店实例一:
```java
public class NYPizzaStore extends PizzaStore {
@Override
Pizza createPizza(String type) {
if("cheese".equals(type)) {
return new NYSytleCheesePizza();
}else {
return null;
}
}
}
```
具体商店实例二:
```java
public class ChicagoStore extends PizzaStore {
@Override
Pizza createPizza(String type) {
if("cheese".equals(type)) {
return new ChicagoStyleCheesePizza();
}else {
return null;
}
}
}
```
定义披萨抽象类
```java
public abstract class Pizza {
String name;
String dough;
String sauce;
ArrayList<String> topping = 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 (String s : topping) {
System.out.println(" "+s);
}
}
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;
}
}
```
创建两个披萨实例
```java
public class NYSytleCheesePizza extends Pizza {
public NYSytleCheesePizza() {
name = "NY style Sause and Cheese Pizza";
dough = "Thin Crust Dough";
sauce = "Marinara Sauce";
topping.add("Grated Reggiano Cheese");
}
}
```
```java
public class ChicagoStyleCheesePizza extends Pizza {
public ChicagoStyleCheesePizza() {
name = "Chicago Style Deep Dish Cheese Pizza";
dough = "Extra Thick Crust Dough";
sauce = "Plum Tomato Sauce";
topping.add("Shredded Mozzarella Cheese");
}
@Override
void cut() {
System.out.println("Cutting the pizza into square slices");
}
}
```
创建测试类
```java
public class PizzaTestStore {
public static void main(String[] args) {
NYPizzaStore ny = new NYPizzaStore();
ChicagoStore ch = new ChicagoStore();
Pizza pizza = ny.orderPizza("cheese");
System.out.println("order a "+pizza.getName());