Abstract factory pattern

The abstract factory pattern provides a way to encapsulate a group of individual factories that have a common theme without specifying their concrete classes.[1] In normal usage, the client software creates a concrete implementation of the abstract factory and then uses the generic interface of the factory to create the concrete objects that are part of the theme. The client does not know (or care) which concrete objects it gets from each of these internal factories, since it uses only the generic interfaces of their products.[1] This pattern separates the details of implementation of a set of objects from their general usage and relies on object composition, as object creation is implemented in methods exposed in the factory interface.[2]
An example of this would be an abstract factory class DocumentCreator
that provides interfaces to create a number of products (e.g. createLetter()
and createResume()
). The system would have any number of derived concrete versions of the DocumentCreator
class like FancyDocumentCreator
or ModernDocumentCreator
, each with a different implementation of createLetter()
and createResume()
that would create a corresponding object like FancyLetter
or ModernResume
. Each of these products is derived from a simple abstract class like Letter
or Resume
of which the client is aware. The client code would get an appropriate instance of the DocumentCreator
and call its factory methods. Each of the resulting objects would be created from the same DocumentCreator
implementation and would share a common theme (they would all be fancy or modern objects). The client would only need to know how to handle the abstract Letter
or Resume
class, not the specific version that it got from the concrete factory.
A factory is the location of a concrete class in the code at which objects are constructed. The intent in employing the pattern is to insulate the creation of objects from their usage and to create families of related objects without having to depend on their concrete classes.[2] This allows for new derived types to be introduced with no change to the code that uses the base class.
Use of this pattern makes it possible to interchange concrete implementations without changing the code that uses them, even at runtime. However, employment of this pattern, as with similar design patterns, may result in unnecessary complexity and extra work in the initial writing of code. Additionally, higher levels of separation and abstraction can result in systems that are more difficult to debug and maintain.
Overview
The Abstract Factory [3] design pattern is one of the twenty-three well-known GoF design patterns that describe how to solve recurring design problems to design flexible and reusable object-oriented software, that is, objects that are easier to implement, change, test, and reuse.
The Abstract Factory design pattern solves problems like: [4]
- How can an application be independent of how its objects are created?
- How can a class be independent of how the objects it requires are created?
- How can families of related or dependent objects be created?
Creating objects directly within the class that requires the objects is inflexible because it commits the class to particular objects and makes it impossible to change the instantiation later independently from (without having to change) the class. It stops the class from being reusable if other objects are required, and it makes the class hard to test because real objects cannot be replaced with mock objects.
The Abstract Factory design pattern describes how to solve such problems:
- Encapsulate object creation in a separate (factory) object. That is, define an interface (AbstractFactory) for creating objects, and implement the interface.
- A class delegates object creation to a factory object instead of creating objects directly.
This makes a class independent of how its objects are created (which concrete classes are instantiated). A class can be configured with a factory object, which it uses to create objects, and even more, the factory object can be exchanged at run-time.
Definition
The essence of the Abstract Factory Pattern is to "Provide an interface for creating families of related or dependent objects without specifying their concrete classes.".[5]
Usage
The factory determines the actual concrete type of object to be created, and it is here that the object is actually created (in C++, for instance, by the new operator). However, the factory only returns an abstract pointer to the created concrete object.
This insulates client code from object creation by having clients ask a factory object to create an object of the desired abstract type and to return an abstract pointer to the object.[6]
As the factory only returns an abstract pointer, the client code (that requested the object from the factory) does not know — and is not burdened by — the actual concrete type of the object that was just created. However, the type of a concrete object (and hence a concrete factory) is known by the abstract factory; for instance, the factory may read it from a configuration file. The client has no need to specify the type, since it has already been specified in the configuration file. In particular, this means:
- The client code has no knowledge whatsoever of the concrete type, not needing to include any header files or class declarations related to it. The client code deals only with the abstract type. Objects of a concrete type are indeed created by the factory, but the client code accesses such objects only through their abstract interface.[7]
- Adding new concrete types is done by modifying the client code to use a different factory, a modification that is typically one line in one file. The different factory then creates objects of a different concrete type, but still returns a pointer of the same abstract type as before — thus insulating the client code from change. This is significantly easier than modifying the client code to instantiate a new type, which would require changing every location in the code where a new object is created (as well as making sure that all such code locations also have knowledge of the new concrete type, by including for instance a concrete class header file). If all factory objects are stored globally in a singleton object, and all client code goes through the singleton to access the proper factory for object creation, then changing factories is as easy as changing the singleton object.[7]
Structure
UML diagram
![A sample UML class and sequence diagram for the Abstract Factory design pattern. [8]](/media/wikipedia/commons/a/aa/W3sDesign_Abstract_Factory_Design_Pattern_UML.jpg)
In the above UML class diagram,
the Client
class that requires ProductA
and ProductB
objects does not instantiate the ProductA1
and ProductB1
classes directly.
Instead, the Client
refers to the AbstractFactory
interface for creating objects,
which makes the Client
independent of how the objects are created (which concrete classes are instantiated).
The Factory1
class implements the AbstractFactory
interface by instantiating the ProductA1
and ProductB1
classes.
The UML sequence diagram shows the run-time interactions:
The Client
object calls createProductA()
on the Factory1
object, which creates and returns a ProductA1
object.
Thereafter,
the Client
calls createProductB()
on Factory1
, which creates and returns a ProductB1
object.
Lepus3 chart
Pseudocode
It should render a button in either a Windows style or Mac OS X style depending on which kind of factory was used. Note that the Application has no idea what kind of GUIFactory
it is given or even what kind of Button
that factory creates.
interface Button is method paint() interface GUIFactory is method createButton() output: a button class WinFactory implementing GUIFactory is method createButton() is output: a Windows button Return a new WinButton class OSXFactory implementing GUIFactory is method createButton() is output: an OS X button Return a new OSXButton class WinButton implementing Button is method paint() is Render a button in a Windows style class OSXButton implementing Button is method paint() is Render a button in a Mac OS X style class Application is constructor Application(factory) is input: the GUIFactory factory used to create buttons Button button := factory.createButton() button.paint() Read the configuration file If the OS specified in the configuration file is Windows, then Construct a WinFactory Construct an Application with WinFactory else Construct an OSXFactory Construct an Application with OSXFactory
C# example
interface IButton
{
void Paint();
}
interface IGUIFactory
{
IButton CreateButton();
}
class WinFactory : IGUIFactory
{
public IButton CreateButton()
{
return new WinButton();
}
}
class OSXFactory : IGUIFactory
{
public IButton CreateButton()
{
return new OSXButton();
}
}
class WinButton : IButton
{
public void Paint()
{
//Render a button in a Windows style
}
}
class OSXButton : IButton
{
public void Paint()
{
//Render a button in a Mac OS X style
}
}
class Program
{
static void Main()
{
var appearance = Settings.Appearance;
IGUIFactory factory;
switch (appearance)
{
case Appearance.Win:
factory = new WinFactory();
break;
case Appearance.OSX:
factory = new OSXFactory();
break;
default:
throw new System.NotImplementedException();
}
var button = factory.CreateButton();
button.Paint();
}
}
Dart example
import "dart:math";
// An existing hierarchy
abstract class Button {
void paint();
}
class WinButton implements Button {
@override
void paint() {
print("WinButton");
}
}
class OSXButton implements Button {
@override
void paint() {
print("OSXButton");
}
}
class LinuxButton implements Button {
@override
void paint() {
print("LinuxButton");
}
}
abstract class GUIFactory {
Button createButton();
}
class WinFactory implements GUIFactory {
@override
Button createButton() {
return WinButton();
}
}
class OSXFactory implements GUIFactory {
@override
Button createButton() {
return OSXButton();
}
}
class LinuxFactory implements GUIFactory {
@override
Button createButton() {
return LinuxButton();
}
}
// Abstract the way to create a button
class AbstractFactory {
static GUIFactory factory(String appearance) {
switch (appearance) {
case "osx":
return OSXFactory();
case "win":
return WinFactory();
case "linux":
return LinuxFactory();
default:
throw "Error";
}
}
}
void main() {
// This is just for the sake of testing this program,
// and does not have to do with the Abstract Factory pattern.
Random _random = Random();
var randomAppearance = ["osx", "win", "linux"].elementAt(_random.nextInt(3));
// get the button factory for an appearance
var guiFactory = AbstractFactory.factory(randomAppearance);
// use the factory to create the button
var button = guiFactory.createButton();
button.paint();
}
Java example
With the introduction of the method reference syntax in Java 8, there is a specific syntax, Type::new, to convert a call to a constructor to a function (typed as a functional interface).
import java.util.List;
import java.util.Random;
// an existing hierarchy
interface Button {
void paint();
}
class WinButton implements Button {
@Override
public void paint() {
System.out.println("WinButton");
}
}
class OSXButton implements Button {
@Override
public void paint() {
System.out.println("OSXButton");
}
}
public class AbstractFactoryExample {
// abstract the way to create a button
@FunctionalInterface
interface GUIFactory {
public Button createButton();
}
class WinFactory implements GUIFactory {
public Button createButton() {
return new WinButton();
}
}
class OSXFactory implements GUIFactory {
public Button createButton() {
return new OSXButton ();
}
}
private static GUIFactory factory(String appearance) {
switch(appearance) {
case "osx":
return new OSXFactory();
case "win":
return new WinFactory();
default:
throw new IllegalArgumentException("unknown " + appearance);
}
}
public static void main(final String[] arguments) {
// This is just for the sake of testing this program,
// and does not have to do with the Abstract Factory pattern.
var randomAppearance = List.of("osx", "win").get(new Random().nextInt(2));
// get the button factory for an appearance
var factory = factory(randomAppearance);
// use the factory to create the button
var button = factory.createButton();
button.paint();
}
}
Also note that instead of declaring the functional interface GUIFactory, it's also possible to use the predefined functional interface java.util.function.Supplier<Button>.
PHP example
interface Button
{
public function paint();
}
interface GUIFactory
{
public function createButton(): Button;
}
class WinFactory implements GUIFactory
{
public function createButton(): Button
{
return new WinButton();
}
}
class OSXFactory implements GUIFactory
{
public function createButton(): Button
{
return new OSXButton();
}
}
class WinButton implements Button
{
public function paint()
{
echo "Windows Button";
}
}
class OSXButton implements Button
{
public function paint()
{
echo "OSX Button";
}
}
$appearance = "osx";
$factory = NULL;
switch ($appearance) {
case "win":
$factory = new WinFactory();
break;
case "osx":
$factory = new OSXFactory();
break;
default:
break;
}
if ($factory instanceof GUIFactory) {
$button = $factory->createButton();
$button->paint();
}
Crystal example
abstract class Button
abstract def paint
end
class LinuxButton < Button
def paint
"Render a button in a Linux style"
end
end
class WindowsButton < Button
def paint
"Render a button in a Windows style"
end
end
class MacOSButton < Button
def paint
"Render a button in a MacOS style"
end
end
abstract class GUIFactory
abstract def create_button : Button
end
class LinuxFactory < GUIFactory
def create_button
return LinuxButton.new
end
end
class WindowsFactory < GUIFactory
def create_button
return WindowsButton.new
end
end
class MacOSFactory < GUIFactory
def create_button
return MacOSButton.new
end
end
# Run program
appearance = "linux"
case appearance
when "linux"
factory = LinuxFactory.new
when "osx"
factory = MacOSFactory.new
when "win"
factory = WindowsFactory.new
end
if factory
button = factory.create_button
result = button.paint
puts result
end
Python example
from __future__ import print_function
from abc import ABCMeta, abstractmethod
class Button:
__metaclass__ = ABCMeta
@abstractmethod
def paint(self):
pass
class LinuxButton(Button):
def paint(self):
return "Render a button in a Linux style"
class WindowsButton(Button):
def paint(self):
return "Render a button in a Windows style"
class MacOSButton(Button):
def paint(self):
return "Render a button in a MacOS style"
class GUIFactory:
__metaclass__ = ABCMeta
@abstractmethod
def create_button(self):
pass
class LinuxFactory(GUIFactory):
def create_button(self):
return LinuxButton()
class WindowsFactory(GUIFactory):
def create_button(self):
return WindowsButton()
class MacOSFactory(GUIFactory):
def create_button(self):
return MacOSButton()
appearance = "linux"
if appearance == "linux":
factory = LinuxFactory()
elif appearance == "osx":
factory = MacOSFactory()
elif appearance == "win":
factory = WindowsFactory()
else:
raise NotImplementedError(
"Not implemented for your platform: {}".format(appearance)
)
if factory:
button = factory.create_button()
result = button.paint()
print(result)
Alternative implementation using the classes themselves as factories:
from __future__ import print_function
from abc import ABCMeta, abstractmethod
class Button:
__metaclass__ = ABCMeta
@abstractmethod
def paint(self):
pass
class LinuxButton(Button):
def paint(self):
return "Render a button in a Linux style"
class WindowsButton(Button):
def paint(self):
return "Render a button in a Windows style"
class MacOSButton(Button):
def paint(self):
return "Render a button in a MacOS style"
appearance = "linux"
if appearance == "linux":
factory = LinuxButton
elif appearance == "osx":
factory = MacOSButton
elif appearance == "win":
factory = WindowsButton
else:
raise NotImplementedError(
"Not implemented for your platform: {}".format(appearance)
)
if factory:
button = factory()
result = button.paint()
print(result)
Golang example
package main
import (
"fmt"
)
type Button interface {
Paint()
}
type GUIFactory interface {
CreateButton() Button
}
type WinFactory struct{}
func (f *WinFactory) CreateButton() Button {
return new(WinButton)
}
type OSXFactory struct{}
func (f *OSXFactory) CreateButton() Button {
return new(OSXButton)
}
type LinuxFactory struct{}
func (f *LinuxFactory) CreateButton() Button {
return new(LinuxButton)
}
type WinButton struct{}
func (b *WinButton) Paint() {
fmt.Println("WinButton")
}
type OSXButton struct{}
func (b *OSXButton) Paint() {
fmt.Println("OSXButton")
}
type LinuxButton struct{}
func (b *LinuxButton) Paint() {
fmt.Println("LinuxButton")
}
func BuildFactory(appearance string) GUIFactory {
switch appearance {
case "Window":
return new(WinFactory)
case "OSX":
return new(OSXFactory)
case "Linux":
return new(LinuxFactory)
}
return nil
}
func main() {
if factory := BuildFactory("Window"); factory != nil {
winButton := factory.CreateButton()
winButton.Paint()
}
if factory := BuildFactory("OSX"); factory != nil {
osxButton := factory.CreateButton()
osxButton.Paint()
}
if factory := BuildFactory("Linux"); factory != nil {
linuxButton := factory.CreateButton()
linuxButton.Paint()
}
}
See also
References
- ^ a b Freeman, Eric; Robson, Elisabeth; Sierra, Kathy; Bates, Bert (2004). Hendrickson, Mike; Loukides, Mike (eds.). Head First Design Patterns (paperback). Vol. 1. O'REILLY. p. 156. ISBN 978-0-596-00712-6. Retrieved 2012-09-12.
- ^ a b Freeman, Eric; Robson, Elisabeth; Sierra, Kathy; Bates, Bert (2004). Hendrickson, Mike; Loukides, Mike (eds.). Head First Design Patterns (paperback). Vol. 1. O'REILLY. p. 162. ISBN 978-0-596-00712-6. Retrieved 2012-09-12.
- ^ Erich Gamma; Richard Helm; Ralph Johnson; John Vlissides (1994). Design Patterns: Elements of Reusable Object-Oriented Software. Addison Wesley. pp. 87ff. ISBN 0-201-63361-2.
- ^ "The Abstract Factory design pattern - Problem, Solution, and Applicability". w3sDesign.com. Retrieved 2017-08-11.
- ^ Gamma, Erich; Richard Helm; Ralph Johnson; John M. Vlissides (2009-10-23). "Design Patterns: Abstract Factory". informIT. Archived from the original on 2009-10-23. Retrieved 2012-05-16.
Object Creational: Abstract Factory: Intent: Provide an interface for creating families of related or dependent objects without specifying their concrete classes.
- ^ Veeneman, David (2009-10-23). "Object Design for the Perplexed". The Code Project. Archived from the original on 2011-09-18. Retrieved 2012-05-16.
The factory insulates the client from changes to the product or how it is created, and it can provide this insulation across objects derived from very different abstract interfaces.
- ^ a b "Abstract Factory: Implementation". OODesign.com. Retrieved 2012-05-16.
- ^ "The Abstract Factory design pattern - Structure and Collaboration". w3sDesign.com. Retrieved 2017-08-12.
External links
- Abstract Factory implementation in Java
Media related to Abstract factory at Wikimedia Commons
- Abstract Factory UML diagram + formal specification in LePUS3 and Class-Z (a Design Description Language)
- Abstract Factory Abstract Factory implementation example