一 、工廠方法(Factory Method)模式
工廠方法模式的意義是定義一個創建產品對象的工廠接口,將實際創建工作推遲到子類當中。核心工廠類不再負責產品的創建,這樣核心類成為一個抽象工廠角色,僅負責具體工廠子類必須實現的接口,這樣進一步抽象化的好處是使得工廠方法模式可以使系統在不修改具體工廠角色的情況下引進新的產品。
二、 工廠方法模式角色與結構
抽象工廠(Creator)角色:是工廠方法模式的核心,與應用程序無關。任何在模式中創建的對象的工廠類必須實現這個接口。
具體工廠(Concrete Creator)角色:這是實現抽象工廠接口的具體工廠類,包含與應用程序密切相關的邏輯,并且受到應用程序調用以創建產品對象。在上圖中有兩個這樣的角色:BulbCreator與TubeCreator。
抽象產品(Product)角色:工廠方法模式所創建的對象的超類型,也就是產品對象的共同父類或共同擁有的接口。在上圖中,這個角色是Light。
具體產品(Concrete Product)角色:這個角色實現了抽象產品角色所定義的接口。某具體產品有專門的具體工廠創建,它們之間往往一一對應。
![]() |
三、一個簡單的實例
// 產品 Plant接口 public interface Plant { } //具體產品PlantA,PlantB public class PlantA implements Plant { public PlantA () { System.out.println("create PlantA !"); } public void doSomething() { System.out.println(" PlantA do something ..."); } } public class PlantB implements Plant { public PlantB () { System.out.println("create PlantB !"); } public void doSomething() { System.out.println(" PlantB do something ..."); } } // 產品 Fruit接口 public interface Fruit { } //具體產品FruitA,FruitB public class FruitA implements Fruit { public FruitA() { System.out.println("create FruitA !"); } public void doSomething() { System.out.println(" FruitA do something ..."); } } public class FruitB implements Fruit { public FruitB() { System.out.println("create FruitB !"); } public void doSomething() { System.out.println(" FruitB do something ..."); } } // 抽象工廠方法 public interface AbstractFactory { public Plant createPlant(); public Fruit createFruit() ; } //具體工廠方法 public class FactoryA implements AbstractFactory { public Plant createPlant() { return new PlantA(); } public Fruit createFruit() { return new FruitA(); } } public class FactoryB implements AbstractFactory { public Plant createPlant() { return new PlantB(); } public Fruit createFruit() { return new FruitB(); } } |
四、工廠方法模式與簡單工廠模式
工廠方法模式與簡單工廠模式再結構上的不同不是很明顯。工廠方法類的核心是一個抽象工廠類,而簡單工廠模式把核心放在一個具體類上。
工廠方法模式之所以有一個別名叫多態性工廠模式是因為具體工廠類都有共同的接口,或者有共同的抽象父類。
當系統擴展需要添加新的產品對象時,僅僅需要添加一個具體對象以及一個具體工廠對象,原有工廠對象不需要進行任何修改,也不需要修改客戶端,很好的符合了"開放-封閉"原則。而簡單工廠模式在添加新產品對象后不得不修改工廠方法,擴展性不好。
工廠方法模式退化后可以演變成簡單工廠模式。