#include <iostream>
#include <string>
using namespace std;
// interface AbstractProductA
class AbstractProductA {
public:
virtual string toString() = 0;
};
// interface AbstractProductB
class AbstractProductB {
public:
virtual string toString() = 0;
};
// interface AbstractFactory
class AbstractFactory {
public:
virtual AbstractProductA *createProductA() = 0;
virtual AbstractProductB *createProductB() = 0;
};
// class ConcreteProductA1 implements AbstractProductA
class ConcreteProductA1 : public AbstractProductA {
public:
string toString() {
return "This is a concrete ProductA for Factory1";
}
};
// class ConcreteProductA2 implements AbstractProductA
class ConcreteProductA2 : public AbstractProductA {
public:
string toString() {
return "This is a concrete ProductA for Factory2";
}
};
// class ConcreteProductB1 implements AbstractProductB
class ConcreteProductB1 : public AbstractProductB {
public:
string toString() {
return "This is a concrete ProductB for Factory1";
}
};
// class ConcreteProductB1 implements AbstractProductB
class ConcreteProductB2 : public AbstractProductB {
public:
string toString() {
return "This is a concrete ProductB for Factory2";
}
};
// class ConcreteFactory1 implements AbstractFactory
class ConcreteFactory1 : public AbstractFactory {
public:
ConcreteFactory1() {}
~ConcreteFactory1() {}
AbstractProductA *createProductA() {
return new ConcreteProductA1();
}
AbstractProductB *createProductB() {
return new ConcreteProductB1();
}
};
// class ConcreteFactory2 implements AbstractFactory
class ConcreteFactory2 : public AbstractFactory {
public:
ConcreteFactory2() {}
~ConcreteFactory2() {}
AbstractProductA *createProductA() {
return new ConcreteProductA2();
}
AbstractProductB *createProductB() {
return new ConcreteProductB2();
}
};
int main(int argc, char **argv) {
AbstractFactory *factory = new ConcreteFactory1(); // Choose a Factory for product A and B.
AbstractProductA *product_a = factory->createProductA(); // create a product A from Factory1
AbstractProductB *product_b = factory->createProductB(); // create a product B from Factory1
cout << product_a->toString() << endl;
cout << product_b->toString() << endl;
delete factory; factory = NULL;
delete product_a; product_a = NULL;
delete product_b; product_b = NULL;
factory = new ConcreteFactory2(); // Choose another Factory for product A and B.
product_a = factory->createProductA(); // create a product A from Factory2
product_b = factory->createProductB(); // create a product B from Factory2
cout << product_a->toString() << endl;
cout << product_b->toString() << endl;
delete factory; factory = NULL;
delete product_a; product_a = NULL;
delete product_b; product_b = NULL;
return 0;
}