Lets take this sentence and figure out what it is.
AbstractFactory pattern uses composition to delegate responsibility of creating object to another class
Abstract Factory can be termed as "Factory of Factory pattern". Here one more class will be there, lets call it FactoryOfFactory
which creates/holds multiple Factories depending on the type of request and returns the end product.
class FactoryOfFactory {
enum Type { P1, P2}
public AbstractProductA createProductA(Type t) {
switch(t) {
case P1:
return new ConcreteFactory1().createProductA();
case P2:
return new ConcreteFactory2().createProductA();
....
}
}
public AbstractProductB createProductB(Type t) {
switch(t) {
case P1:
return new ConcreteFactory1().createProductB();
case P2:
return new ConcreteFactory2().createProductB();
....
}
}
}
The definition of Composition is
Composition is a special case of aggregation. In a more specific manner, a restricted aggregation is called composition. When an object contains the other object, if the contained object cannot exist without the existence of container object, then it is called composition.
Here the container is FactoryOfFactory
and the contained objects are different implementation of Factory classes such as ConcreteFactory1
, ConcreteFactory2
etc. FactoryOfFactory
delegates the request to respective factory implementation depending on Type