一 、工廠方法(Factory Method)模式
工廠方法模式的意義是定義一個(gè)創(chuàng)建產(chǎn)品對(duì)象的工廠接口,將實(shí)際創(chuàng)建工作推遲到子類當(dāng)中。核心工廠類不再負(fù)責(zé)產(chǎn)品的創(chuàng)建,這樣核心類成為一個(gè)抽象工廠角色,僅負(fù)責(zé)具體工廠子類必須實(shí)現(xiàn)的接口,這樣進(jìn)一步抽象化的好處是使得工廠方法模式可以使系統(tǒng)在不修改具體工廠角色的情況下引進(jìn)新的產(chǎn)品。
二、 工廠方法模式角色與結(jié)構(gòu)
抽象工廠(Creator)角色:是工廠方法模式的核心,與應(yīng)用程序無關(guān)。任何在模式中創(chuàng)建的對(duì)象的工廠類必須實(shí)現(xiàn)這個(gè)接口。
具體工廠(Concrete Creator)角色:這是實(shí)現(xiàn)抽象工廠接口的具體工廠類,包含與應(yīng)用程序密切相關(guān)的邏輯,并且受到應(yīng)用程序調(diào)用以創(chuàng)建產(chǎn)品對(duì)象。在上圖中有兩個(gè)這樣的角色:BulbCreator與TubeCreator。
抽象產(chǎn)品(Product)角色:工廠方法模式所創(chuàng)建的對(duì)象的超類型,也就是產(chǎn)品對(duì)象的共同父類或共同擁有的接口。在上圖中,這個(gè)角色是Light。
具體產(chǎn)品(Concrete Product)角色:這個(gè)角色實(shí)現(xiàn)了抽象產(chǎn)品角色所定義的接口。某具體產(chǎn)品有專門的具體工廠創(chuàng)建,它們之間往往一一對(duì)應(yīng)。
三、一個(gè)簡(jiǎn)單的實(shí)例
// 產(chǎn)品 Plant接口 public interface Plant { } //具體產(chǎn)品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 ..."); } } // 產(chǎn)品 Fruit接口 public interface Fruit { } //具體產(chǎn)品FruitA,F(xiàn)ruitB 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(); } } |
四、工廠方法模式與簡(jiǎn)單工廠模式
工廠方法模式與簡(jiǎn)單工廠模式再結(jié)構(gòu)上的不同不是很明顯。工廠方法類的核心是一個(gè)抽象工廠類,而簡(jiǎn)單工廠模式把核心放在一個(gè)具體類上。
工廠方法模式之所以有一個(gè)別名叫多態(tài)性工廠模式是因?yàn)榫唧w工廠類都有共同的接口,或者有共同的抽象父類。
當(dāng)系統(tǒng)擴(kuò)展需要添加新的產(chǎn)品對(duì)象時(shí),僅僅需要添加一個(gè)具體對(duì)象以及一個(gè)具體工廠對(duì)象,原有工廠對(duì)象不需要進(jìn)行任何修改,也不需要修改客戶端,很好的符合了"開放-封閉"原則。而簡(jiǎn)單工廠模式在添加新產(chǎn)品對(duì)象后不得不修改工廠方法,擴(kuò)展性不好。
工廠方法模式退化后可以演變成簡(jiǎn)單工廠模式。