The abstract factory pattern helps to create families of related objects through the use of individual factories.
One key insight (which was helpful to me) is to fully grasp "families of related objects". Using the Wikipedia diagram for reference here, something to observe here are the products created from the concrete factories. Observe the products created from within each factory are slotted to the interface. where , concrete factories. Thus, client is returned products and here unaware of the underlying implementation.
Code Example (Java)
Demonstrated here abridged with some code snips.
// Abstract Factory
interface IAbstractFactory {
public IComponentA createComponentA();
public IComponentB createComponentB();
// ...
}
interface IComponentA {};
interface IComponentB {};
public class JPaekComponentA implements IComponentA {};
public class JPaekComponentB implements IComponentB {};
public class JPaekFactory implements IAbstractFactory {
public IComponentA createA() { return new JPaekComponentA(); }
public IComponentB createB() { return new JPaekComponentB(); }
}
// ...
Client retrieves objects via factory.
import IAbstractFactory;
import IComponentA;
import IComponentB;
public class Client {
public static void main(String args[]) {
IAbstractFactory f = new JPaekFactory();
IComponentA a = f.createComponentA();
IComponentB b = f.createComponentB();
}
}
The reference to the factory can be determined run-time or compiled-time depending on what is required of the system.
UML Refresher
- When
realizing
aninterface
a dashed-line is used to the interface, arrow closed and unfilled. - When
generalizing
, a solid-line is used, arrow closed and unfilled. - Weak forms of
association
are indicated with a dashed-line and open arrow.
Typically a «stereotype»
is placed on the assocation describing the action.