抽象工厂模式针对的是产品族,而不是产品等级结构。
产品族:同一产地或者同一产商,功能不同。
产品等级:功能相同,产地或者厂商不同。
代码如下:
#include <iostream>
using namespace std;class AbstractApple
{
public:virtual void showName() = 0;
};class ChinaApple :public AbstractApple
{
public:virtual void showName(){cout << "中国苹果" << endl;}
};class UsaApple :public AbstractApple
{
public:virtual void showName(){cout << "美国苹果" << endl;}
};class JapanApple :public AbstractApple
{
public:virtual void showName(){cout << "日本苹果" << endl;}
};class AbstractBanana
{
public:virtual void showName() = 0;
};class ChinaBanana :public AbstractBanana
{
public:virtual void showName(){cout << "中国香蕉" << endl;}
};class UsaBanana :public AbstractBanana
{
public:virtual void showName(){cout << "美国香蕉" << endl;}
};class JapanBanana :public AbstractBanana
{
public:virtual void showName(){cout << "日本香蕉" << endl;}
};class AbstractPear
{
public:virtual void showName() = 0;
};class ChinaPear :public AbstractPear
{
public:virtual void showName(){cout << "中国梨子" << endl;}
};class UsaPear :public AbstractPear
{
public:virtual void showName(){cout << "美国梨子" << endl;}
};class JapanPear :public AbstractPear
{
public:virtual void showName(){cout << "日本梨子" << endl;}
};class AbstractFactory
{
public:virtual AbstractApple *CreateApple() = 0;virtual AbstractBanana *CreateBanana() = 0;virtual AbstractPear *CreatePear() = 0;
};class ChinaFactory :public AbstractFactory
{
public:virtual AbstractApple *CreateApple(){return new ChinaApple;}virtual AbstractBanana *CreateBanana(){return new ChinaBanana;}virtual AbstractPear *CreatePear(){return new ChinaPear;}
};class UsaFactory :public AbstractFactory
{
public:virtual AbstractApple *CreateApple(){return new UsaApple;}virtual AbstractBanana *CreateBanana(){return new UsaBanana;}virtual AbstractPear *CreatePear(){return new UsaPear;}
};class JapanFactory :public AbstractFactory
{
public:virtual AbstractApple *CreateApple(){return new JapanApple;}virtual AbstractBanana *CreateBanana(){return new JapanBanana;}virtual AbstractPear *CreatePear(){return new JapanPear;}
};void test01()
{AbstractFactory *factory = nullptr;AbstractApple *apple = nullptr;AbstractBanana *banana = nullptr;AbstractPear *pear = nullptr;factory = new ChinaFactory;apple = factory->CreateApple();banana = factory->CreateBanana();pear = factory->CreatePear();apple->showName();banana->showName();pear->showName();//与构造的顺序相反,倒着deletedelete pear;delete banana;delete apple;delete factory;
}int main()
{test01();return 0;
}
测试结果: