1简介
抽象工厂模式是所有形态的工厂模式中最为抽象和最其一般性的。抽象工厂模式可以向客户端提供一个接口,使得客户端在不必指定产品的具体类型的情况下,能够创建多个产品族的产品对象。
2 举例
工厂即生产CPU又生产内存。
class CPU
{
public:
virtual void getCPU() = 0;
};
class Memory
{
public:
virtual void getMemory() = 0;
};
class IBMCPU:public CPU
{
public:
void getCPU()
{
cout << "i am IBM CPU" << endl;
}
};
class DELLCPU :public CPU
{
public:
void getCPU()
{
cout << "i am dell CPU." << endl;
}
};
class IBMMemory :public Memory
{
public:
void getMemory()
{
cout << "i am IBM Memory" << endl;
}
};
class DELLMemory :public Memory
{
public:
void getMemory()
{
cout << "i am dell Memory." << endl;
}
};
class Factory
{
public:
virtual CPU* getProductCPU() = 0;
virtual Memory* getProductMemory() = 0;
};
class IBMFactory :public Factory
{
public:
CPU* getProductCPU()
{
return new IBMCPU;
}
Memory* getProductMemory()
{
return new IBMMemory;
}
};
class DELLFactory :public Factory
{
public:
CPU* getProductCPU()
{
return new DELLCPU;
}
Memory* getProductMemory()
{
return new DELLMemory;
}
};
int main()
{
Factory* factory = NULL;
factory = new IBMFactory;
CPU * cpu = NULL;
Memory *mem = NULL;
cpu = factory->getProductCPU();
mem = factory->getProductMemory();
cpu->getCPU();
mem->getMemory();
delete factory;
delete cpu;
delete mem;
return 1;
}