# 工廠模式 Factory 一個class當作工廠,會負責回傳出相對樣的其他class。 舉例來說有一個class叫做factory,他的工作是負責生產card,所以我們還要生成各個card的class,當我們使用factory的create方法的時候會回傳一個給card的class給我們。 ```java= public abstract class Factory { //先以 createProduct 製作產品,再以 registerProduct 完成登錄 public final Product create(String owner) { Product p = createProduct(owner); registerProduct(p); return p; } protected abstract Product createProduct(String owner); protected abstract void registerProduct(Product product); } public class IDCardFactory extends Factory { private Vector owners = new Vector(); protected Product createProduct(String owner) { return new IDCard(owner); } protected void registerProduct(Product product) { owners.add(((IDCard)product).getOwner()); } public Vector getOwners() { return owners; } } public abstract class Product { public abstract void use(); } public class IDCard extends Product { private String owner; //只能夠在同一個 package 中呼叫建構子 IDCard(String owner) { System.out.println("建立" + owner + "的卡。"); this.owner = owner; } public void use () { System.out.println("使用" + owner + "的卡。"); } public String getOwner() { return owner; } } public class Main { public static void main(String[] args) { Factory factory = new IDCardFactory(); Product card1 = factory.create("結城浩"); Product card2 = factory.create("戶村"); Product card3 = factory.create("佐藤花子"); card1.use(); card2.use(); card3.use(); } } ``` > [name=閔致] # The differences between "Factory Method" and "Simple Factory Method". ## 工廠模式和簡單工廠模式的差別。 Suppose we have these code. ```java= public interface Pizza{ void print(); } public class NewYorkPizza implements Pizza{ public void print(){ System.out.println("I am NY Pizza"); } } public class ChicagoPizza implements Pizza{ public void print(){ System.out.println("I am Chicago Pizza"); } } ``` Here is the code for the Factory Method. ```java= public abstract class PizzaFactory{ Pizza getInstance(); } public class NewYorkPizza extends PizzaFactory{ Pizza getInstance(){ return new NewYorkPizza(); } } public class ChicagoPizza extends PizzaFactory{ Pizza getInstance(){ return new ChicagoPizza(); } } ``` Here is the code for the Simple Factory Method. ```java= public class SimplePizzaFactory{ public Pizza getInstance(String type){ switch(type){ case "NY": return new NewYorkPizza(); case "Chicago": return new ChicagoPizza(); default: return null; } } } ``` ### To sum up, in the Factory Method, each Concrete Factory decides which product would be instantiate. However Simple Factory Method would create the object by the "type" that client passed in. > [name=YuanChangLee]
{"metaMigratedAt":"2023-06-16T11:21:14.949Z","metaMigratedFrom":"YAML","title":"工廠模式 Factory","breaks":true,"contributors":"[{\"id\":\"8602dcf8-b376-48f8-a0d2-0e6b1bcbfd92\",\"add\":1615,\"del\":262},{\"id\":\"1880e957-c482-42c0-815b-4a0ded0c27a0\",\"add\":2874,\"del\":1271},{\"id\":\"82eaa412-2ff3-4bfe-bbd7-5ff190dd3326\",\"add\":30,\"del\":0}]"}
Expand menu