[Design Pattern] 抽象工廠模式
阿新 • • 發佈:2018-06-01
app 開閉原則 分離 virtual turn name delet () 改進
工廠方法模式
讓一個具體的類對應一個工廠。然後把所有工廠進行抽象。通過抽象工廠實現具體的工廠來創建對象。如果需要新增一個類,那麽就需要創建一個工廠類來創建對象
優點:
1. 符合開閉原則。是簡單工廠改進
2. 實現創建和使用分離
缺點:
1. 類的個數龐大。增加一個具體對象類就需要增加一個對應工廠類。增加維護成本
參考代碼:
class Fruit { public: virtual void showName() = 0; }; class Apple : public Fruit { public: virtual void showName() { cout<< "I am apple." << endl; } }; class Banana : public Fruit { public: virtual void showName() { cout << "I am banana." << endl; } }; class Pear : public Fruit { public: virtual void showName() { cout << "I am pear." << endl; } };class FactoryMethod { public: virtual Fruit* createFruit() = 0; }; class AppleFactory : public FactoryMethod { public: virtual Fruit* createFruit() { return new Apple(); } }; class BananaFactory : public FactoryMethod { public: virtual Fruit* createFruit() { returnnew Banana(); } }; class PearFactory : public FactoryMethod { public: virtual Fruit* createFruit() { return new Pear(); } }; int main() { FactoryMethod* factory = new AppleFactory(); Fruit* apple = factory->createFruit(); apple->showName(); delete factory; delete apple; return 0; }
適用場景
1. 客戶端不知道它鎖需要對象的類
2. 抽象工廠類通過其子類來指定創建哪個對象
[Design Pattern] 抽象工廠模式