抽象工厂模式是有多个抽象产品时,使用的工厂模式。抽象工厂模式可以向客户端提供接口,使用户在不指定具体产品的情况下,创建多个产品族中产品的对象。
下面我们用一个例子来说明抽象工厂模式,再下面的例子中,有两个产品族:中餐和西餐。产品族中有产品主食和甜点:
#include "stdafx.h"
#include <iostream>
using namespace std;
// 抽象产品接口
class Staple
{
public:
virtual void Show() = 0;
};
class Dessert
{
public:
virtual void Show() = 0;
};
// 产品族1,中餐
class RiseStaple : public Staple
{
public:
void Show()
{
cout << "im rice; staple of chinese food" << endl;
}
};
class SpringRollDessert : public Dessert
{
public:
void Show()
{
cout << "im sprint roll; dessert of chinese food" << endl;
}
};
// 产品族2,西餐
class SteakStaple : public Staple
{
public:
void Show()
{
cout << "im steak; staple of western food" << endl;
}
};
class PieDessert : public Dessert
{
public:
void Show()
{
cout << "im pie; staple of western food" << endl;
}
};
// 抽象工厂类
class Factory
{
public:
virtual Staple* GetStaple() = 0;
virtual Dessert* GetDessert() = 0;
};
// 具体工厂类
class ChineseFoodFactory : public Factory
{
public:
Staple* GetStaple()
{
return new RiseStaple();
}
Dessert* GetDessert()
{
return new SpringRollDessert();
}
};
class WesternFoodFacotry : public Factory
{
public:
Staple* GetStaple()
{
return new SteakStaple();
}
Dessert* GetDessert()
{
return new PieDessert();
}
};
void PrepareFood(Factory* factory)
{
Staple* staple = factory->GetStaple();
Dessert* dessert = factory->GetDessert();
staple->Show();
dessert->Show();
cout << "done..." << endl;
delete factory;
delete staple;
delete dessert;
}
int main()
{
PrepareFood(new ChineseFoodFactory());
PrepareFood(new WesternFoodFacotry());
system("pause");
return 0;
}
代码执行结果如下:
im rice; staple of chinese food
im sprint roll; dessert of chinese food
done…
im steak; staple of western food
im pie; staple of western food
done…
从例子中可以看出,抽象工厂模式有点像是工厂方法模式的加强版。工厂方法模式每个具体工厂只能生成单一的产品,但是抽象方法模式一个具体工厂可以生产多个产品。所以,工厂方法模式比较适合产品结构单一的场景,但是抽象工厂模式适合于产品结构复杂的场景;每个具体工厂提供一组相关或者相互依赖的对象。
抽象工厂模式也保证了多个对象一起工作的时候,这些对象一定是一个产品族中的,比如上例中,我们要吃中餐就所有的食物都是中餐,不会牛排和春卷一起混着吃。