什么都不用说,直接贴代码,已运行过。
//抽象的工厂方法
#include "iostream"方法
using namespace std;
class ProductA
{
public:
virtual void show() = 0;
};
class ProductA1 : public ProductA
{
public:
void show()
{
cout<<"I'm ProductA1" << endl;
}
};
class ProductA2 : public ProductA
{
public:
void show()
{
cout<<"I'm ProductA2" << endl;
}
};
class ProductB
{
public:
virtual void show() = 0;
};
class ProductB1 : public ProductB
{
public:
void show()
{
cout<<"I'm ProductB1" << endl;
}
};
class ProductB2 : public ProductB
{
public:
void show()
{
cout<<"I'm ProductB2" << endl;
}
};
//工厂方法
class Factory
{
public:
virtual ProductA *createProductA() = 0;
virtual ProductB *createProductB() = 0;
};
class Factory1 : public Factory
{
public:
ProductA *createProductA()
{
return new ProductA1();
}
ProductB *createProductB()
{
return new ProductB1();
}
};
class Factory2 : public Factory
{
public:
ProductA *createProductA()
{
return new ProductA2();
}
ProductB *createProductB()
{
return new ProductB2();
}
};
int main(int argc, char const *argv[])
{
Factory *factoryObj1 = new Factory1();
ProductA *productObjA1 = factoryObj1->createProductA();
ProductB *productObjB1 = factoryObj1->createProductB();
productObjA1->show();
productObjB1->show();
Factory *factoryObj2 = new Factory2();
ProductA *productObjA2 = factoryObj2->createProductA();
ProductB *productObjB2 = factoryObj2->createProductB();
productObjA2->show();
productObjB2->show();
return 0;
}