设计模式——抽象工厂模式(C++实现)

时间:2024-10-09 11:38:14

设计模式——抽象工厂模式(C++实现)

设计模式——抽象工厂模式(C++实现)

 #include <iostream>
#include <string> using namespace std; class STAbstractProductA
{
public:
virtual void use() = ;
}; class STProductA1: public STAbstractProductA
{
public:
virtual void use()
{
cout<< "use ProductA1............"<< endl;
}
}; class STProductA2: public STAbstractProductA
{
public:
virtual void use()
{
cout<< "use ProductA2............"<< endl;
}
}; class STAbstractProductB
{
public:
virtual void eat() = ;
}; class STProductB1: public STAbstractProductB
{
public:
virtual void eat()
{
cout<< "eat ProductB1............"<< endl;
}
}; class STProductB2: public STAbstractProductB
{
public:
virtual void eat()
{
cout<< "eat ProductB2............"<< endl;
}
}; class STAbstractFactory
{
public:
virtual STAbstractProductA* CreateProductA() = ;
virtual STAbstractProductB* CreateProductB() = ;
}; class STConcreteFactoryA: public STAbstractFactory
{
public:
virtual STAbstractProductA* CreateProductA()
{
return new STProductA1;
}
virtual STAbstractProductB* CreateProductB()
{
return new STProductB1;
}
}; class STConcreteFactoryB: public STAbstractFactory
{
public:
virtual STAbstractProductA* CreateProductA()
{
return new STProductA2;
}
virtual STAbstractProductB* CreateProductB()
{
return new STProductB2;
}
}; int main(int argc, char* argv[])
{
STAbstractFactory* fc = new STConcreteFactoryA();
STAbstractProductA* pa = fc->CreateProductA();
STAbstractProductB* pb = fc->CreateProductB(); pa->use();
pb->eat(); STAbstractFactory* fc2 = new STConcreteFactoryB();
STAbstractProductA* pa2 = fc2->CreateProductA();
STAbstractProductB* pb2 = fc2->CreateProductB(); pa2->use();
pb2->eat(); return ;
}
////////////////////////////////////////
[root@ ~/learn_code/design_pattern/9_abstract_factory]$ ./abstract_factory
use ProductA1............
eat ProductB1............
use ProductA2............
eat ProductB2............

相关文章