The abstract factory pattern helps to create families of related objects through the use of individual factories.
The key insight is understanding what is meant here by "families of related objects".
Outline
-
Create an abstract factory and abstract methods to create the desired products.
-
The products should be of a generic form to enforce encapsulation.
-
Implement the concrete factories.
where f, concrete factory.
- Client is returned products of interface form and unaware of the underlying implementation.
In this example, we'll assume the client's factory is determined at compile-time. It should be seen it can also be determined during run-time.
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.