解決的問題:
類圖結構:
樣例實現:
// CplusplusAbstractFactory.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include<typeinfo>
// "AbstractProductA" 草食動物
class Herbivore
{
};
// "AbstractProductB" 食肉動物
class Carnivore
{
public:
// Methods
virtual void Eat( Herbivore *h ) {};
};
// "ProductA1"
class Wildebeest : public Herbivore
{
};
// "ProductA2"
class Bison : public Herbivore
{
};
// "ProductB1"
class Lion : public Carnivore
{
public:
// Methods
void Eat( Herbivore *h )
{
// eat wildebeest
printf("Lion eats %s\n",typeid(h).name());
}
};
// "ProductB2"
class Wolf : public Carnivore
{
public:
// Methods
void Eat( Herbivore *h )
{
// Eat bison
printf("Wolf eats %s\n",typeid(h).name());
}
};
// "AbstractFactory"
class ContinentFactory
{
public:
// Methods
virtual Herbivore* CreateHerbivore()
{
return new Herbivore();
}
virtual Carnivore* CreateCarnivore()
{
return new Carnivore();
}
};
// "ConcreteFactory1"
class AfricaFactory : public ContinentFactory
{
public:
// Methods
Herbivore* CreateHerbivore()
{
return new Wildebeest();
}
Carnivore* CreateCarnivore()
{
return new Lion();
}
};
// "ConcreteFactory2"
class AmericaFactory : public ContinentFactory
{
public:
// Methods
Herbivore* CreateHerbivore()
{
return new Bison();
}
Carnivore* CreateCarnivore()
{
return new Wolf();
}
};
// "Client"
class AnimalWorld
{
private:
// Fields
Herbivore* herbivore;
Carnivore* carnivore;
public:
// Constructors
AnimalWorld( ContinentFactory *factory )
{
carnivore = factory->CreateCarnivore();
herbivore = factory->CreateHerbivore();
}
// Methods
void RunFoodChain()
{
carnivore->Eat(herbivore);
}
};
int _tmain(int argc, _TCHAR* argv[])
{
// Create and run the Africa animal world
ContinentFactory *africa = new AfricaFactory();
AnimalWorld *world = new AnimalWorld( africa );
world->RunFoodChain();
// Create and run the America animal world
ContinentFactory *america = new AmericaFactory();
world = new AnimalWorld( america );
world->RunFoodChain();
return 0;
}
“開放-封閉”原則:
實現要點:
- 在抽象工廠模式中,選用哪種產品族的問題,需要採用工廠方法或簡單工廠模式來配合解決。
- 抽象工廠模式和工廠方法模式一樣,都把對象的創建延遲到了他的子類中。
- 具體的工廠類可以設計成單例類,他只向外界提供自己唯一的實例。
與其他工廠模式的聯繫和異同:
- 抽象工廠模式中的具體工廠負責生產一個產品族的產品。而產品族的增加只需要增加與其對應的具體工廠。
- 3種工廠模式都是創建型模式,都是創建對象的,但都把產品具體創建的過程給隱藏了。
- 工廠方法模式是針對一種產品結構,而抽象工廠模式是針對多種產品結構。
適用性:
在以下情況下應當考慮使用抽象工廠模式:
- 一個系統不應當依賴於產品類實例如何被創建、組合和表達的細節,這對於所有形態的工廠模式都是重要的。
- 這個系統有多於一個的產品族,而系統只消費其中某一產品族。
- 同屬於同一個產品族的產品是在一起使用的,這一約束必須在系統的設計中體現出來。
- 系統提供一個產品類的庫,所有的產品以同樣的接口出現,從而使客戶端不依賴於實現。
應用場景:
- 支持多種觀感標準的用戶界面工具箱(Kit)。
- 遊戲開發中的多風格系列場景,比如道路,房屋,管道等。