简述
举例:北京分店和上海分店,能生产当地口味的奶酪Pizza和素食Pizza。
代码
各种Pizza
/**
* 制作pizza 接口
* @author ydfind
* @date 2019.10.14
*/
public abstract class Pizza1 {
/**
* 准备
*/
public void prepare(){
}
/**
* 烘烤
*/
public void bake(){
}
/**
* 切片
*/
public void cut(){
}
/**
* 装盒
*/
public void box(){
}
}
/**
* 北京风味 奶酪Pizza
*/
public class BeijingCheesePizza extends Pizza1 {
@Override
public void prepare() {
System.out.println("这是一个 北京风味 奶酪Pizza");
}
}
package com.ydfind.gof.factory.factorymethod;
/**
* 北京风味 素食Pizza
* @author ydfind
* @date 2019.10.14
*/
public class BeijingVeggiePizza extends Pizza1 {
@Override
public void prepare() {
System.out.println("这是一个北京风味 素食Pizza");
}
}
/**
* 上海风味 奶酪Pizza
*/
public class ShangHaiCheesePizza extends Pizza1 {
@Override
public void prepare() {
System.out.println("这是一个 上海风味 奶酪Pizza");
}
}
/**
* 上海风味 素食Pizza
* @author ydfind
* @date 2019.10.14
*/
public class ShangHaiVeggiePizza extends Pizza1 {
@Override
public void prepare() {
System.out.println("这是一个上海风味 素食Pizza");
}
}
Pizza店
/**
* Pizza店
* @author ydfind
* @date 2019.10.25
*/
public abstract class PizzaStore1 {
public static final String CHEESE_PIZZA = "奶酪Pizza";
public static final String VEGGIE_PIZZA = "素食Pizza";
public Pizza1 orderPizza(String type){
Pizza1 pizza;
pizza = createPizza(type);
pizza.prepare();
pizza.bake();
pizza.cut();
pizza.box();
return pizza;
}
protected abstract Pizza1 createPizza(String type);
}
/**
* 北京Pizza店
*/
public class BeijingPizzaStore extends PizzaStore1 {
@Override
protected Pizza1 createPizza(String type) {
switch (type){
case CHEESE_PIZZA:
return new BeijingCheesePizza();
case VEGGIE_PIZZA:
return new BeijingVeggiePizza();
default:
return null;
}
}
}
/**
* 上海Pizza店
*/
public class ShangHaiPizzaStore extends PizzaStore1 {
@Override
protected Pizza1 createPizza(String type) {
switch (type){
case CHEESE_PIZZA:
return new ShangHaiCheesePizza();
case VEGGIE_PIZZA:
return new ShangHaiVeggiePizza();
default:
return null;
}
}
}
使用示例及测试
@Test
public void testFactoryMethod(){
System.out.println("*********************工厂方法 测试********************************");
PizzaStore1 shanghaiStore = new ShangHaiPizzaStore();
PizzaStore1 beijingStore = new BeijingPizzaStore();
shanghaiStore.orderPizza(PizzaStore1.CHEESE_PIZZA);
beijingStore.orderPizza(PizzaStore1.VEGGIE_PIZZA);
}