Abstract Factory
The abstract factory pattern provides a way to encapsulate a group of individual factories that have a common theme without specifying their concrete classes. 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. 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. 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. 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 which are more difficult to debug and maintain. Therefore, as in all software designs, the trade-offs must be carefully evaluated.
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".
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.
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.
- 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.
Structure
Class diagram
The method createButton
on the GuiFactory
interface returns objects of type Button
. What implementation of Button
is returned depends on which implementation of GuiFactory
is handling the method call.
Note that, for conciseness, this class diagram only shows the class relations for creating one type of object.
Lepus3 chart (legend)
UML diagram
Implementations
The output should be either "I'm a WinButton" or "I'm an OSXButton" 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.
/* GUIFactory example -- */
using System;
using System.Configuration;
namespace AbstractFactory {
public interface IButton {
void Paint();
}
public interface IGUIFactory {
IButton CreateButton();
}
public class OSXButton : IButton { // Executes fourth if OS:OSX
public void Paint() {
System.Console.WriteLine("I'm an OSXButton");
}
}
public class WinButton : IButton { // Executes fourth if OS:WIN
public void Paint() {
System.Console.WriteLine("I'm a WinButton");
}
}
public class OSXFactory : IGUIFactory { // Executes third if OS:OSX
IButton IGUIFactory.CreateButton() {
return new OSXButton();
}
}
public class WinFactory : IGUIFactory { // Executes third if OS:WIN
IButton IGUIFactory.CreateButton() {
return new WinButton();
}
}
public class Application {
public Application(IGUIFactory factory) {
IButton button = factory.CreateButton();
button.Paint();
}
}
public class ApplicationRunner {
static IGUIFactory CreateOsSpecificFactory() { // Executes second
// Contents of App.Config associated with this C# project
//<?xml version="1.0" encoding="utf-8" ?>
//<configuration>
// <appSettings>
// <!-- Uncomment either Win or OSX OS_TYPE to test -->
// <add key="OS_TYPE" value="Win" />
// <!-- <add key="OS_TYPE" value="OSX" /> -->
// </appSettings>
//</configuration>
string sysType = ConfigurationSettings.AppSettings["OS_TYPE"];
if (sysType == "Win") {
return new WinFactory();
} else {
return new OSXFactory();
}
}
static void Main() { // Executes first
new Application(CreateOsSpecificFactory());
Console.ReadLine();
}
}
}
/* GUIFactory example */
#include <iostream>
class Button {
public:
virtual void paint() = 0;
virtual ~Button() { }
};
class WinButton : public Button {
public:
void paint() {
std::cout << "I'm a WinButton";
}
};
class OSXButton : public Button {
public:
void paint() {
std::cout << "I'm an OSXButton";
}
};
class GUIFactory {
public:
virtual Button* createButton() = 0;
virtual ~GUIFactory() { }
};
class WinFactory : public GUIFactory {
public:
Button* createButton() {
return new WinButton();
}
~WinFactory() { }
};
class OSXFactory : public GUIFactory {
public:
Button* createButton() {
return new OSXButton();
}
~OSXFactory() { }
};
class Application {
public:
Application(GUIFactory* factory) {
Button* button = factory->createButton();
button->paint();
delete button;
delete factory;
}
};
GUIFactory* createOsSpecificFactory() {
int sys;
std::cout << "Enter OS type (0: Windows, 1: MacOS X): ";
std::cin >> sys;
if (sys == 0) {
return new WinFactory();
} else {
return new OSXFactory();
}
}
int main() {
Application application(createOsSpecificFactory());
return 0;
}
/* GUIFactory example -- */
interface Button {
void paint();
}
interface GUIFactory {
Button createButton();
}
class WinFactory implements GUIFactory {
public Button createButton() {
return new WinButton();
}
}
class OSXFactory implements GUIFactory {
public Button createButton() {
return new OSXButton();
}
}
class WinButton implements Button {
public void paint() {
System.out.println("I'm a WinButton");
}
}
class OSXButton implements Button {
public void paint() {
System.out.println("I'm an OSXButton");
}
}
class Application {
public Application(GUIFactory factory) {
Button button = factory.createButton();
button.paint();
}
}
public class ApplicationRunner {
public static void main(String[] args) {
new Application(createOsSpecificFactory());
}
public static GUIFactory createOsSpecificFactory() {
int sys = readFromConfigFile("OS_TYPE");
if (sys == 0) return new WinFactory();
else return new OSXFactory();
}
}
/* GUIFactory example -- */
#import <Foundation/Foundation.h>
@protocol Button <NSObject>
- (void)paint;
@end
@interface WinButton : NSObject <Button>
@end
@interface OSXButton : NSObject <Button>
@end
@protocol GUIFactory
- (id<Button>)createButton;
@end
@interface WinFactory : NSObject <GUIFactory>
@end
@interface OSXFactory : NSObject <GUIFactory>
@end
@interface Application : NSObject
- (id)initWithGUIFactory:(id)factory;
+ (id)createOsSpecificFactory:(int)type;
@end
@implementation WinButton
- (void)paint {
NSLog(@"I am a WinButton.");
}
@end
@implementation OSXButton
- (void)paint {
NSLog(@"I am a OSXButton.");
}
@end
@implementation WinFactory
- (id<Button>)createButton {
return [[[WinButton alloc] init] autorelease];
}
@end
@implementation OSXFactory
- (id<Button>)createButton {
return [[[OSXButton alloc] init] autorelease];
}
@end
@implementation Application
- (id)initWithGUIFactory:(id<GUIFactory>)factory {
if (self = [super init]) {
id button = [factory createButton];
[button paint];
}
return self;
}
+ (id<GUIFactory>)createOsSpecificFactory:(int)type {
if (type == 0) {
return [[[WinFactory alloc] init] autorelease];
} else {
return [[[OSXFactory alloc] init] autorelease];
}
}
@end
int main(int argc, char* argv[]) {
@autoreleasepool {
[[Application alloc] initWithGUIFactory:[Application createOsSpecificFactory:0]];// 0 is WinButton
}
return 0;
}
--[[
Because Lua is a highly dynamic Language, an OOP scheme is implemented by the programmer.
The OOP scheme implemented here implements interfaces using documentation.
A Factory Supports:
- factory:CreateButton()
A Button Supports:
- button:Paint()
]]
-- Create the OSXButton Class
do
OSXButton = {}
local mt = { __index = OSXButton }
function OSXButton:new()
local inst = {}
setmetatable(inst, mt)
return inst
end
function OSXButton:Paint()
print("I'm a fancy OSX button!")
end
end
-- Create the WinButton Class
do
WinButton = {}
local mt = { __index = WinButton }
function WinButton:new()
local inst = {}
setmetatable(inst, mt)
return inst
end
function WinButton:Paint()
print("I'm a fancy Windows button!")
end
end
-- Create the OSXGuiFactory Class
do
OSXGuiFactory = {}
local mt = { __index = OSXGuiFactory }
function OSXGuiFactory:new()
local inst = {}
setmetatable(inst, mt)
return inst
end
function OSXGuiFactory:CreateButton()
return OSXButton:new()
end
end
-- Create the WinGuiFactory Class
do
WinGuiFactory = {}
local mt = { __index = WinGuiFactory }
function WinGuiFactory:new()
local inst = {}
setmetatable(inst, mt)
return inst
end
function WinGuiFactory:CreateButton()
return WinButton:new()
end
end
-- Table to keep track of what GuiFactories are available
GuiFactories = {
["Win"] = WinGuiFactory,
["OSX"] = OSXGuiFactory,
}
--[[ Inside an OS config script ]]
OS_VERSION = "Win"
--[[ Using the Abstract Factory in some the application script ]]
-- Selecting the factory based on OS version
MyGuiFactory = GuiFactories[OS_VERSION]:new()
-- Using the factory
osButton = MyGuiFactory:CreateButton()
osButton:Paint()
This abstract factory creates books.
/*
* BookFactory classes
*/
abstract class AbstractBookFactory {
abstract function makePHPBook();
abstract function makeMySQLBook();
}
class OReillyBookFactory extends AbstractBookFactory {
private $context = "OReilly";
function makePHPBook() {
return new OReillyPHPBook;
}
function makeMySQLBook() {
return new OReillyMySQLBook;
}
}
class SamsBookFactory extends AbstractBookFactory {
private $context = "Sams";
function makePHPBook() {
return new SamsPHPBook;
}
function makeMySQLBook() {
return new SamsMySQLBook;
}
}
/*
* Book classes
*/
abstract class AbstractBook {
abstract function getAuthor();
abstract function getTitle();
}
abstract class AbstractMySQLBook extends AbstractBook {
private $subject = "MySQL";
}
class OReillyMySQLBook extends AbstractMySQLBook {
private $author;
private $title;
function __construct() {
$this->author = 'George Reese, Randy Jay Yarger, and Tim King';
$this->title = 'Managing and Using MySQL';
}
function getAuthor() {
return $this->author;
}
function getTitle() {
return $this->title;
}
}
class SamsMySQLBook extends AbstractMySQLBook {
private $author;
private $title;
function __construct() {
$this->author = 'Paul Dubois';
$this->title = 'MySQL, 3rd Edition';
}
function getAuthor() {
return $this->author;
}
function getTitle() {
return $this->title;
}
}
abstract class AbstractPHPBook extends AbstractBook {
private $subject = "PHP";
}
class OReillyPHPBook extends AbstractPHPBook {
private $author;
private $title;
private static $oddOrEven = 'odd';
function __construct() {
//alternate between 2 books
if ('odd' == self::$oddOrEven) {
$this->author = 'Rasmus Lerdorf and Kevin Tatroe';
$this->title = 'Programming PHP';
self::$oddOrEven = 'even';
} else {
$this->author = 'David Sklar and Adam Trachtenberg';
$this->title = 'PHP Cookbook';
self::$oddOrEven = 'odd';
}
}
function getAuthor() {
return $this->author;
}
function getTitle() {
return $this->title;
}
}
class SamsPHPBook extends AbstractPHPBook {
private $author;
private $title;
function __construct() {
//alternate randomly between 2 books
mt_srand((double)microtime() * 10000000);
$rand_num = mt_rand(0, 1);
if (1 > $rand_num) {
$this->author = 'George Schlossnagle';
$this->title = 'Advanced PHP Programming';
}
else {
$this->author = 'Christian Wenz';
$this->title = 'PHP Phrasebook';
}
}
function getAuthor() {
return $this->author;
}
function getTitle() {
return $this->title;
}
}
/*
* Initialization
*/
writeln('BEGIN TESTING ABSTRACT FACTORY PATTERN');
writeln('');
writeln('testing OReillyBookFactory');
$bookFactoryInstance = new OReillyBookFactory;
testConcreteFactory($bookFactoryInstance);
writeln('');
writeln('testing SamsBookFactory');
$bookFactoryInstance = new SamsBookFactory;
testConcreteFactory($bookFactoryInstance);
writeln("END TESTING ABSTRACT FACTORY PATTERN");
writeln('');
function testConcreteFactory($bookFactoryInstance) {
$phpBookOne = $bookFactoryInstance->makePHPBook();
writeln('first php Author: '.$phpBookOne->getAuthor());
writeln('first php Title: '.$phpBookOne->getTitle());
$phpBookTwo = $bookFactoryInstance->makePHPBook();
writeln('second php Author: '.$phpBookTwo->getAuthor());
writeln('second php Title: '.$phpBookTwo->getTitle());
$mySqlBook = $bookFactoryInstance->makeMySQLBook();
writeln('MySQL Author: '.$mySqlBook->getAuthor());
writeln('MySQL Title: '.$mySqlBook->getTitle());
}
function writeln($line_in) {
echo $line_in."<br/>";
}
This abstract factory creates musicians.
// concrete implementation
class DrummerFactory extends MusicianAbstractFactory {
def create(): Musician = new Drummer()
}
class GuitarPlayerFactory extends MusicianAbstractFactory {
def create(): Musician = new GuitarPlayer()
}
class GuitarPlayer extends Musician {
def play(song: String) {
println(s"I'm guitar player and I play $song")
}
}
class Drummer extends Musician {
def play(song: String) {
println(s"I'm drummer and I play '$song'")
}
}
object FactoryCreator {
def getFactory(config: Boolean): MusicianAbstractFactory =
if (config) {
new DrummerFactory
} else {
new GuitarPlayerFactory
}
}
// interfaces to import
trait Musician {
def play(song: String)
}
trait MusicianAbstractFactory {
def create(): Musician
}
import implementation.FactoryCreator
object AbstractFactoryTest {
def readFromConfig(): Boolean = true
def main(args: Array[String]) {
val factory = FactoryCreator.getFactory(readFromConfig())
val musician = factory.create()
musician.play("Highway to hell")
}
}
from abc import ABC, abstractmethod
from sys import platform
class Button(ABC):
@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(ABC):
@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()
if platform == "linux":
factory = LinuxFactory()
elif platform == "darwin":
factory = MacOSFactory()
elif platform == "win32":
factory = WindowsFactory()
else:
raise NotImplementedError(f"Not implemented for your platform: {platform}")
button = factory.create_button()
result = button.paint()
print(result)
Alternative implementation using the classes themselves as factories:
from abc import ABC, abstractmethod
from sys import platform
class Button(ABC):
@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"
if platform == "linux":
factory = LinuxButton
elif platform == "darwin":
factory = MacOSButton
elif platform == "win32":
factory = WindowsButton
else:
raise NotImplementedError(f"Not implemented for your platform: {platform}")
button = factory()
result = button.paint()
print(result)
Another example:
import platform
class GuiFactory():
"""Abstract Factory"""
@classmethod
def getFactory(Class):
if platform.system() == "Windows":
return WinFactory()
elif platform.system() == "OSX":
return OSXFactory()
elif platform.system() == "Linux":
return LinuxFactory()
class Button:
""" Abstract Product"""
def paint(self):
raise NotImplementedError
@classmethod
def getButton(Class):
return Class.Button()
class WinFactory(GuiFactory):
"""Concrete Factory"""
class Button(GuiFactory.Button):
"""Concrete Product"""
def paint(self):
print "I am a Windows button"
class LinuxFactory(GuiFactory):
"""Concrete Factory"""
class Button(GuiFactory.Button):
"""Concrete Product"""
def paint(self):
print "I am a Linux button"
class OSXFactory(GuiFactory):
"""Concrete Factory"""
class Button(GuiFactory.Button):
"""Concrete Product"""
def paint(self):
print "I am a OSX button"
def main():
"""Application"""
factory = GuiFactory.getFactory()
factory.getButton().paint()
if __name__ == "__main__":
main()
program AbstractFactory;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils;
type
(* abstract factory *)
TAbstractFactory = class abstract
procedure Paint(); virtual; abstract;
end;
(* abstract product *)
TGUIFactory = class abstract
function CreateButton(): TAbstractFactory; virtual; abstract;
end;
(* concrete product *)
TOSXButton = class(TAbstractFactory)
public
procedure Paint(); override;
end;
(* concrete product *)
TWinButton = class(TAbstractFactory)
public
procedure Paint(); override;
end;
(* concrete factory *)
TOSXFactory = class(TGUIFactory)
public
function CreateButton(): TAbstractFactory; override;
end;
(* concrete factory *)
TWinFactory = class(TGUIFactory)
public
function CreateButton(): TAbstractFactory; override;
end;
(* client *)
TApplication = class
public
constructor Create(factory: TGUIFactory);
end;
(* Just for OOP style use class. This function is to return button factory only. *)
TApplicationRunner = class
public
class function CreateOsSpecificFactory: TGUIFactory;
end;
{ TOSXButton }
procedure TOSXButton.Paint;
begin
WriteLn('I`m an OSXButton');
end;
{ TWinButton }
procedure TWinButton.Paint;
begin
WriteLn('I`m a WinButton');
end;
{ TOSXFactory }
function TOSXFactory.CreateButton: TAbstractFactory;
begin
Result := TOSXButton.Create;
end;
{ TWinFactory }
function TWinFactory.CreateButton: TAbstractFactory;
begin
Result := TWinButton.Create;
end;
{ TApplication }
constructor TApplication.Create(factory: TGUIFactory);
var
button: TAbstractFactory;
begin
button := factory.CreateButton;
button.Paint;
end;
{ TApplicationRunner }
class function TApplicationRunner.CreateOsSpecificFactory: TGUIFactory;
var
sysType: string;
begin
WriteLn('Enter OS type (Win: Windows, OSX: MacOS X)');
ReadLn(sysType);
if (sysType = 'Win') then
Result := TWinFactory.Create
else
Result := TOSXFactory.Create
end;
var
App: TApplication;
begin
try
{ TODO -oUser -cConsole Main : Insert code here }
App := TApplication.Create(TApplicationRunner.CreateOsSpecificFactory);
WriteLn(#13#10 + 'Press any key to continue...');
ReadLn;
App.Free;
except
on E: Exception do
WriteLn(E.ClassName, ': ', E.Message);
end;
end.