抽象工厂模式
定义: 为创建一组相关或相互依赖的对象提供一个接口, 而且无须指定它们的具体类。
// abstract productA
class abstractProductA
{
public:
abstractProductA() {}
virtual ~abstractProductA() {}
public:
virtual void doSomething() = 0;
};
// abstract productB
class abstractProductB
{
public:
abstractProductB() {}
virtual ~abstractProductB() {}
public:
virtual void doSomething() = 0;
};
// abstract creator(factory)
class abstractCreator
{
public:
abstractCreator() {}
virtual ~abstractCreator() {}
public:
virtual abstractProductA* createProductA() = 0;
virtual abstractProductB* createProductB() = 0;
};
// concrete product A1
class productA1 : public abstractProductA
{
public:
productA1() {}
~productA1() {}
public:
virtual void doSomething() {
std::cout << "I'm proudct A1..." << std::endl;
}
};
// concrete product A2
class productA2 : public abstractProductA
{
public:
productA2() {}
~productA2() {}
public:
virtual void doSomething() {
std::cout << "I'm proudct A2..." << std::endl;
}
};
// concrete product B1
class productB1 : public abstractProductB
{
public:
productB1() {}
~productB1() {}
public:
virtual void doSomething() {
std::cout << "I'm proudct B1..." << std::endl;
}
};
// concrete product B2
class productB2 : public abstractProductB
{
public:
productB2() {}
~productB2() {}
public:
virtual void doSomething() {
std::cout << "I'm proudct B2..." << std::endl;
}
};
// concrete creator 1
class concreteCreator1 :public abstractCreator
{
public:
concreteCreator1() {}
~concreteCreator1() {}
public:
virtual abstractProductA* createProductA() {
return new productA1();
}
virtual abstractProductB* createProductB() {
return new productB1();
}
};
// concrete creator 2
class concreteCreator2 :public abstractCreator
{
public:
concreteCreator2() {}
~concreteCreator2() {}
public:
virtual abstractProductA* createProductA() {
return new productA2();
}
virtual abstractProductB* createProductB() {
return new productB2();
}
};
void test_AbstractFactory(){
abstractCreator* cretor1 = new concreteCreator1();
abstractCreator* cretor2 = new concreteCreator2();
abstractProductA* a1 = cretor1->createProductA();
abstractProductA* a2 = cretor2->createProductA();
abstractProductB* b1 = cretor1->createProductB();
abstractProductB* b2 = cretor2->createProductB();
a1->doSomething();
a2->doSomething();
b1->doSomething();
b2->doSomething();
delete cretor1;
delete cretor2;
delete a1;
delete a2;
delete b1;
delete b2;
}