Provides an interface for creating different instances of the same parent type
Use when:
Example C++ Code
// the Abstract Factory Class
class AbstractFactory
{
public:
virtual AbstractProductA CreateProductA() = 0;
virtual AbstractProductB CreateProductB() = 0;
};
// one factory implementation
class ConcreteFactory1 : public AbstractFactory
{
public:
ConcreteFactory1();
~ConcreteFactory1();
// we'll assume ConcreteProductA1 and A2 are
// defined elsewhere and inherit from AbstractProductA
AbstractProductA CreateProductA() {
ConcreteProductA1 a1;
return a1;
}
AbstractProductB CreateProductB() {
ConcreteProductB1 b1;
return b1;
}
};
// another factory implementation
class ConcreteFactory2 : public AbstractFactory
{
public:
ConcreteFactory2();
~ConcreteFactory2();
// again, assume *ProductA2 and B2 are defined elsewhere
AbstractProductA CreateProductA() = {
ConcreteProductA2 a2;
return a2;
}
AbstractProductB CreateProductB() {
ConcreteProductB2 b2;
return b2;
}
};
// now this class will use the abstract factory which will
// be one of the two Concrete* classes, and can be swapped
// with a single line of code
class UsingClass
{
public:
// either of the two factories can be sent here and even
// be changed during runtime
void setProductFactory(AbstractFactory *factory)
{
productFactory = factory;
}
void initProducts()
{
productA = productFactory->CreateProductA();
productB = productFactory->CreateProductB();
}
private:
AbstractFactory *productFactory;
AbstractProductA productA;
AbstractProductB productB;
};