資源描述:
《Java設(shè)計模式之抽象工廠模式》由會員上傳分享,免費在線閱讀,更多相關(guān)內(nèi)容在學(xué)術(shù)論文-天天文庫。
1、一、抽象工廠模式(AbstractFactory)抽象工廠模式提供一個創(chuàng)建一系列相關(guān)或相互依賴對象的接口,而無需指定它們具體的類。抽象工廠(AbstractFactory)模式,又稱工具箱(Kit或Toolkit)模式。二、創(chuàng)建過程如下一個具體工廠創(chuàng)建一個產(chǎn)品族,一個產(chǎn)品族是不同系列產(chǎn)品的組合,產(chǎn)品的創(chuàng)建的邏輯分在在每個具體工廠類中。所有的具體工廠繼承自同一個抽象工廠。客戶端創(chuàng)建不同產(chǎn)品族的工廠,產(chǎn)品族的工廠創(chuàng)建具體的產(chǎn)品對客戶端是不可見的。增加新的產(chǎn)品族時,需要增加具體工廠類,符合OCP原則。增加新產(chǎn)品時,需要修改具體工廠類和增加產(chǎn)品類,不符合
2、OCP原則如果沒有應(yīng)對“多系列對象創(chuàng)建”的需求變化,則沒有必要使用抽象工廠模式,這時候使用簡單的靜態(tài)工廠完全可以。三、一個簡單的實例//產(chǎn)品Plant接口publicinterfaceIPlant{}//具體產(chǎn)品PlantA,PlantBpublicclassPlantAimplementsIPlant{publicPlantA(){System.out.println("createPlantA!");}publicvoiddoSomething(){System.out.println("PlantAdosomething...");}}pu
3、blicclassPlantBimplementsIPlant{publicPlantB(){System.out.println("createPlantB!");}publicvoiddoSomething(){System.out.println("PlantBdosomething...");}}//產(chǎn)品Fruit接口publicinterfaceIFruit{}//具體產(chǎn)品FruitA,F(xiàn)ruitBpublicclassFruitAimplementsIFruit{publicFruitA(){System.out.println("c
4、reateFruitA!");}publicvoiddoSomething(){System.out.println("FruitAdosomething...");}}publicclassFruitBimplementsIFruit{publicFruitB(){System.out.println("createFruitB!");}publicvoiddoSomething(){System.out.println("FruitBdosomething...");}}//抽象工廠方法publicinterfaceAbstractFacto
5、ry{publicIPlantcreatePlant();publicIFruitcreateFruit();}//具體工廠方法publicclassFactoryAimplementsAbstractFactory{publicIPlantcreatePlant(){returnnewPlantA();}publicIFruitcreateFruit(){returnnewFruitA();}}publicclassFactoryBimplementsAbstractFactory{publicIPlantcreatePlant(){retur
6、nnewPlantB();}publicIFruitcreateFruit(){returnnewFruitB();}}