工廠方法模式(Factory Pattern)屬於『創建型模式』。
定義了一個建立物件的介面,但由次類別決定實體化的類別為何者。工廠方法讓類別將實體化的動作,交由次類別進行。 工廠方法是一個抽象的方法,依賴次類別負責物件的建立。
public interface Pizza {
public String getName();
public void prepaid();
public void baking();
}
public class NYBeefPizza implements Pizza{
@Override
public String getName() {
return "牛肉Pizza";
}
@Override
public void prepaid() {
System.out.println(getName()+" 準備中...");
System.out.println(getName()+" 加入紐約特製醬料...");
}
@Override
public void baking() {
System.out.println(getName()+" 烘烤中...");
}
}
public class TPSeafoodPizza implements Pizza{
@Override
public String getName() {
return "海鮮Pizza";
}
@Override
public void prepaid() {
System.out.println(getName()+" 準備中...");
System.out.println(getName()+" 加入臺北特製醬料...");
}
@Override
public void baking() {
System.out.println(getName()+" 烘烤中...");
}
}
public abstract class PizzaFactory {
public enum PIZZATYPE{
BEEF,SEAFOOD;
}
public Pizza orderPizza(PIZZATYPE pizzaType){
System.out.println(getClass()+" 開始準備Pizza");
Pizza pizza = createPizza(pizzaType);
pizza.prepaid();
pizza.baking();
return pizza;
}
protected abstract Pizza createPizza(PIZZATYPE pizzaType);
}
public class NewYorkPizzaFactory extends PizzaFactory {
@Override
protected Pizza createPizza(PIZZATYPE pizzaType) {
Pizza pizza = null;
if(pizzaType == PIZZATYPE.BEEF){
pizza = new NYBeefPizza();
}else if(pizzaType == PIZZATYPE.SEAFOOD){
pizza = new NYSeafoodPizza();
}
return pizza;
}
}
public class TaipeiPizzaFactory extends PizzaFactory {
@Override
protected Pizza createPizza(PIZZATYPE pizzaType) {
Pizza pizza = null;
if(pizzaType == PIZZATYPE.BEEF){
pizza = new TPBeefPizza();
}else if(pizzaType == PIZZATYPE.SEAFOOD){
pizza = new TPSeafoodPizza();
}
return pizza;
}
}
public static void main(String args[]) {
String people1 = "客人1";
String people2 = "客人2";
System.out.println(people1+ " 想購買紐約pizze");
System.out.println(people2+ " 想購買臺北pizza");
PizzaFactory callFactory = null;
callFactory = new NewYorkPizzaFactory();
Pizza nySeafoodPizza= callFactory.orderPizza(PIZZATYPE.SEAFOOD);
System.out.println(people1 + " get:"+nySeafoodPizza.getName());
callFactory = new TaipeiPizzaFactory();
Pizza tpBeefPizza= callFactory.orderPizza(PIZZATYPE.BEEF);
System.out.println(people2 + " get:"+tpBeefPizza.getName());
}
客人1 想購買紐約pizze
客人2 想購買臺北pizza
NewYorkPizzaFactory 開始準備Pizza
海鮮Pizza 準備中...
海鮮Pizza 加入紐約特製醬料...
海鮮Pizza 烘烤中...
客人1 get:海鮮Pizza
TaipeiPizzaFactory 開始準備Pizza
牛肉Pizza 準備中...
牛肉Pizza 加入臺北特製醬料...
牛肉Pizza 烘烤中...
客人2 get:牛肉Pizza