Computer Science Design Patterns/Print version

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.

Implementation in C#
/* 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();
        }
    }
}
Implementation in C++
/* 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;
}
Implementation in Java
/* 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();
    }
}
Implementation in Objective-C
/* 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;
}
Implementation in Lua
--[[
    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()
Implementation in PHP

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/>";
}
Implementation in Scala

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")
  }
}
Implementation in Python
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()
Implementation in Delphi
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.

Adapter

The adapter pattern is used when a client class has to call an incompatible provider class. Let's imagine a MailingClient class that needs to call a method on the LegacyEmployee class:

MailingClient
+firstName: String
+lastName: String
 
IEmployee
+mailEmployee(firstName: String, lastName: String)
 
LegacyEmployee
+mailEmployee(fullName: String)

MailingClient already calls classes that implement the IEmployee interface but the LegacyEmployee doesn't implement it. We could add a new method to LegacyEmployee to implement the IEmployee interface but LegacyEmployee is legacy code and can't be changed. We could modify the MailingClient class to call LegacyEmployee but it needs to change every call. The formatting code would be duplicated everywhere. Moreover, MailingClient won't be able to call other provider class that implement the IEmployee interface any more.

So the solution is to code the formatting code in another independent class, an adapter, also called a wrapper class:

IEmployee
+mailEmployee(firstName: String, lastName: String)
 
MailingClient
+firstName: String
+lastName: String
 
EmployeeAdapter
+mailEmployee(firstName: String, lastName: String)
 
LegacyEmployee
+mailEmployee(fullName: String)

EmployeeAdapter implements the IEmployee interface. MailingClient calls EmployeeAdapter. EmployeeAdapter formats the data and calls LegacyEmployee. This type of adapter is called an object adapter. The other type of adapter is the class adapter.


 

To do:
Describe the class adapter.


Examples

The WebGL-2D is a JavaScript library that implements the adapter pattern. This library is used for the HTML5 canvas element. The canvas element has two interfaces: 2d and WebGL. The first one is very simple to use and the second is much more complex but optimized and faster. The WebGL-2D 'adapts' the WebGL interface to the 2d interface, so that the client calls the 2d interface only.

Cost

Think twice before implementing this pattern. This pattern should not be planned at design time. If you plan to use it for a project from scratch, this means that you don't understand this pattern. It should be used only with legacy code. It is the least bad solution.

Creation

Its implementation is easy but can be expensive. You should not have to refactor the code as the client and the provider should not be able to work together yet.

Maintenance

This is the worst part. Most of the code has redundancies (but less than without the pattern). The modern interface should always provide as much information as the legacy interface needs to work. If one information is missing on the modern interface, it can call the pattern into question.

Removal

This pattern can be easily removed as automatic refactoring operations can easily remove its existence.

Advices

  • Put the adapter term in the name of the adapter class to indicate the use of the pattern to the other developers.

Implementation

Object Adapter

Implementation in Java

Our company has been created by a merger. One list of employees is available in a database you can access via the CompanyAEmployees class:

/**
 * Employees of the Company A.
 */
public class CompanyAEmployees {
  /**
   * Retrieve the employee information from the database.
   *
   * @param sqlQuery The SQL query.
   * @return The employee object.
   */
  public Employee getEmployee(String sqlQuery) {
      Employee employee = null;
     
      // Execute the request.
     
      return employee;
    }
}

One list of employees is available in a LDAP you can access via the CompanyBEmployees class:

/**
 * Employees of the Company B.
 */
public class CompanyBEmployees {
  /**
   * Retrieve the employee information from the LDAP.
   *
   * @param sqlQuery The SQL query.
   * @return The employee object.
   */
  public Employee getEmployee(String distinguishedName) {
      Employee employee = null;
     
      // Call the LDAP.
     
      return employee;
    }
}

To access both to the former employees of the company A and the former employees of the company B, we define an interface that will be used by two adapters, EmployeeBrowser:

/**
 * Retrieve information about the employees.
 */
interface EmployeeBrowser {
  /**
   * Retrieve the employee information.
   *
   * @param direction The employee direction.
   * @param division The employee division.
   * @param department The employee departement.
   * @param service The employee service.
   * @param firstName The employee firstName.
   * @param lastName The employee lastName.
   *
   * @return The employee object.
   */
  Employee getEmployee(String direction, String division, String department, String service, String firstName, String lastName);
}

We create an adapter for the code of the former company A, CompanyAAdapter:

/**
 * Adapter for the company A legacy code.
 */
public class CompanyAAdapter implements EmployeeBrowser {
  /**
   * Retrieve the employee information.
   *
   * @param direction The employee direction.
   * @param division The employee division.
   * @param department The employee department.
   * @param service The employee service.
   * @param firstName The employee firstName.
   * @param lastName The employee lastName.
   *
   * @return The employee object.
   */
  public Employee getEmployee(String direction, String division, String department, String service, String firstName, String lastName) {
    String distinguishedName = "SELECT *"
      + " FROM t_employee as employee"
      + " WHERE employee.company= 'COMPANY A'"
      + " AND employee.direction = " + direction
      + " AND employee.division = " + division
      + " AND employee.department = " + department
      + " AND employee.service = " + service
      + " AND employee.firstName = " + firstName
      + " AND employee.lastName = " + lastName;
   
    CompanyAEmployees companyAEmployees = new CompanyAEmployees();
    return companyAEmployees.getEmployee(distinguishedName);
  }
}

We create an adapter for the code of the former company B, CompanyBAdapter:

/**
 * Adapter for the company B legacy code.
 */
public class CompanyBAdapter implements EmployeeBrowser {
  /**
   * Retrieve the employee information.
   *
   * @param direction The employee direction.
   * @param division The employee division.
   * @param department The employee department.
   * @param service The employee service.
   * @param firstName The employee firstName.
   * @param lastName The employee lastName.
   *
   * @return The employee object.
   */
  public Employee getEmployee(String direction, String division, String department, String service, String firstName, String lastName) {
    String distinguishedName = "ov1 = " + direction
      + ", ov2 = " + division
      + ", ov3 = " + department
      + ", ov4 = " + service
      + ", cn = " + firstName + lastName;
   
    CompanyBEmployees companyBEmployees = new CompanyBEmployees();
    return companyBEmployees.getEmployee(distinguishedName);
  }
}
Implementation in Ruby

Ruby

class Adaptee
  def specific_request
    # do something
  end
end

class Adapter
  def initialize(adaptee)
    @adaptee = adaptee
  end

  def request
    @adaptee.specific_request
  end
end

client = Adapter.new(Adaptee.new)
client.request
Implementation in Python
class Adaptee:
    def specific_request(self):
        return 'Adaptee'
 
class Adapter:
    def __init__(self, adaptee):
        self.adaptee = adaptee
 
    def request(self):
        return self.adaptee.specific_request()
 
client = Adapter(Adaptee())
print client.request()
Implementation in Scala
trait Socket220V {
  def plug220()
}

trait Socket19V {
  def plug19()
}

class Laptop extends Socket19V {
  def plug19() {
    println("Charging....")
  }
}

class LaptopAdapter(laptop: Laptop) extends Socket220V {
  def plug220() {
    println("Transform1...")
    laptop.plug19()
  }
}

object Test {
  def main(args: Array[String]) {
    //you can do it like this:
    new LaptopAdapter(new Laptop).plug220()

    //or like this (doesn't need LaptopAdapter)
    new Laptop with Socket220V {
      def plug220() {
        println("Transform2...")
        this.plug19()
      }
    } plug220()
  }
}
Implementation in Delphi
program Adapter;

{$APPTYPE CONSOLE}
{$R *.res}

uses
  System.SysUtils;

type
  (* Its interface *)
  TTarget = class abstract
    function Request: string; virtual; abstract;
  end;

  (* A client accessed to this. *)
  TAdaptee = class(TTarget)
    function Request: string; override;
  end;

  (* Object Adapter uses composition and can wrap classes or interfaces, or both.*)
  (* Redirect call to Adaptee. It is loose coupling of client and adapter.*)
  (*
    *It can do this since it contains, as a private, encapsulated member,
    *the class or interface object instance it wraps.
  *)
  TObjectAdapter = class
    fAdaptee: TAdaptee;
    function SpecialRequest: string;
    constructor Create(adaptee: TAdaptee);
  end;

  { TObjectAdapter }

constructor TObjectAdapter.Create;
begin
  fAdaptee := TAdaptee.Create;
end;

function TObjectAdapter.SpecialRequest: string;
begin
  Result := fAdaptee.Request;
end;

{ TAdaptee }

function TAdaptee.Request: string;
begin
  Result := 'Adaptee';
end;

var
  clientObject: TObjectAdapter;

begin
  try
    { TODO -oUser -cConsole Main : Insert code here }
    clientObject := TObjectAdapter.Create(TAdaptee.Create);

    WriteLn('Call method Object Adapter: '+clientObject.SpecialRequest);

    WriteLn(#13#10+ 'Press any key to continue...');
    ReadLn;

    clientObject.Free;
  except
    on E: Exception do
      WriteLn(E.ClassName, ': ', E.Message);
  end;

end.


Class Adapter

Implementation in Python
class Adaptee1:
    def __init__(self, *args, **kw):
        pass
   
    def specific_request(self):
        return 'Adaptee1'

class Adaptee2:
    def __init__(self, *args, **kw):
        pass
   
    def specific_request(self):
        return 'Adaptee2'
 
class Adapter(Adaptee1, Adaptee2):
    def __init__(self, *args, **kw):
        Adaptee1.__init__(self, *args, **kw)
        Adaptee2.__init__(self, *args, **kw)
 
    def request(self):
        return Adaptee1.specific_request(self), Adaptee2.specific_request(self)
 
client = Adapter()
print client.request()
Implementation in Delphi
program Adapter;

{$APPTYPE CONSOLE}
{$R *.res}

uses
  System.SysUtils;

type
  (* Its interface *)
  TTarget = class abstract
    function Request: string; virtual; abstract;
  end;

  (* A client accessed to this. *)
  TAdaptee = class(TTarget)
    function Request: string; override;
  end;

  (* Class Adapter uses inheritance and can only wrap a class.*)
  (* This plain old inheritance. *)
  (* It cannot wrap an interface since by definition*)
  (* it must derive from some base class as Adaptee in example*)
  (*
    * Can't reuse Class Adapter without rewrite code
    * You need implements other adapter with other method in other class.
  *)
   TClassAdapter = class(TAdaptee)
   function SpecialRequest: string;
   end;

{ TClassAdapter }

function TClassAdapter.SpecialRequest: string;
begin
  //use inherited Request as SpecialRequest
  Result:= inherited Request;
end;

{ TAdaptee }

function TAdaptee.Request: string;
begin
  Result := 'Adaptee';
end;

var
  clientClass:TClassAdapter;

begin
  try
    { TODO -oUser -cConsole Main : Insert code here }
    clientClass:= TClassAdapter.Create;

    WriteLn('Call method Class Adapter: '+clientClass.SpecialRequest);

    WriteLn(#13#10+ 'Press any key to continue...');
    ReadLn;

    clientClass.Free;
  except
    on E: Exception do
      WriteLn(E.ClassName, ': ', E.Message);
  end;

end.

Bridge

Bridge pattern is useful when a code often changes for an implementation as well as for a use of code. In your application, you should have provider classes and client classes:

Client1
-provider: Provider
 
Client2
-provider: Provider
...
ClientN
-provider: Provider
◊—
Provider
+doProcess()
 
 
...
 
Provider1
+doProcess()
Provider2
+doProcess()
...
ProviderN
+doProcess()

Each client class can interact with each provider class. However, if the implementation changes, the method signatures of the Provider interface may change and all the client classes have to change. In the same way, if the client classes need a new interface, we need to rewrite all the providers. The solution is to add a bridge, that is to say a class that will be called by the clients, that contains a reference to the providers and forward the client call to the providers.

Client1
-bridge: Bridge
 
Client2
-bridge: Bridge
...
ClientN
-bridge: Bridge
◊—
Bridge
-provider: Provider
+doProcessForClient()
◊—
Provider
+doProcess()
 
 
...
 
Provider1
+doProcess()
Provider2
+doProcess()
...
ProviderN
+doProcess()

In the future, the two interfaces (client/bridge and bridge/provider) may change independently and the bridge may trans-code the call order.

Examples

It's hard to find an example in a library as this pattern is designed for versatile specifications and a library does not change constantly between two versions.

Cost

The cost of this pattern is the same as the adapter. It can be planned at design time but the best way to decide to add it is the experience feedback. Implement it when you have frequently changed an interface in a short time.

Creation

Its implementation is easy but can be expensive. It depends on the complexity of the interface. The more methods you have, the more expensive it will be.

Maintenance

If you always update the client/bridge interface and the bridge/provider interface the same way, it would be more expensive than if you do not implement the design pattern.

Removal

This pattern can be easily removed as automatic refactoring operations can easily remove its existence.

Advices

  • Put the bridge term in the name of the bridge class to indicate the use of the pattern to the other developers.

Implementation

Implementation in Kotlin
/** "Implementor" */
fun interface MusicPlayer {
    fun play(song: String): String
}

/** "ConcreteImplementor" 1/4 */
val defaultPlayer = MusicPlayer{
    "Reproducing $it in ${MusicFormat.NONE}"
}

/** "ConcreteImplementor" 2/4 */
val mp3Player = MusicPlayer{
    "Reproducing $it in ${MusicFormat.MP3}"
}

/** "ConcreteImplementor" 3/4 */
val mp4Player = MusicPlayer{
    "Reproducing $it in ${MusicFormat.MP4}"
}

/** "ConcreteImplementor" 4/4 */
val vlcPlayer = MusicPlayer{
    "Reproducing \"$it\" in ${MusicFormat.VLC}"
}

/** "Abstraction" */
abstract class MusicPlayerUI {
    var musicPlayer : MusicPlayer = defaultPlayer
    abstract fun playMusic(song: String, musicFormat: MusicFormat)
}

 /** "Refined Abstraction" */
class MyMusicPlayerUI : MusicPlayerUI() {
    override fun playMusic(song: String, musicFormat: MusicFormat) {
        musicPlayer = when(musicFormat) {
            MusicFormat.NONE -> defaultPlayer
            MusicFormat.MP3 -> mp3Player
            MusicFormat.MP4 -> mp4Player
            MusicFormat.VLC -> vlcPlayer
        }
        println(musicPlayer.play(song))
    }

}

enum class MusicFormat{
    NONE,MP3,MP4,VLC
}

 /** "Client" */
object BridgePattern {
    @JvmStatic
    fun main(args: Array<String>) {
        val musicPlayer = MyMusicPlayerUI()
        musicPlayer.playMusic("The best song", MusicFormat.MP4)
    }
}
Implementation in Java

The following Java (SE 6) program illustrates the bridge pattern.

/**
 * Implementor
 */
interface DrawingAPI {
    public void drawCircle(double x, double y, double radius);
}
/**
 * ConcreteImplementor  1/2
 */
class DrawingAPI1 implements DrawingAPI {
   public void drawCircle(double x, double y, double radius) {
        System.out.printf("API1.circle at %f:%f radius %f\n", x, y, radius);
   }
}
/**
 * ConcreteImplementor 2/2
 */
class DrawingAPI2 implements DrawingAPI {
   public void drawCircle(double x, double y, double radius) {
        System.out.printf("API2.circle at %f:%f radius %f\n", x, y, radius);
   }
}
/**
 * Abstraction
 */
abstract class Shape {
   protected DrawingAPI drawingAPI;

   protected Shape(DrawingAPI drawingAPI) {
      this.drawingAPI = drawingAPI;
   }

   public abstract void draw();                             // low-level
   public abstract void resizeByPercentage(double pct);     // high-level
}
/**
 * Refined Abstraction
 */
class CircleShape extends Shape {
   private double x, y, radius;
   public CircleShape(double x, double y, double radius, DrawingAPI drawingAPI) {
      super(drawingAPI);
      this.x = x;
      this.y = y;
      this.radius = radius;
   }

   // low-level i.e. Implementation specific
   public void draw() {
        drawingAPI.drawCircle(x, y, radius);
   }

   // high-level i.e. Abstraction specific
   public void resizeByPercentage(double pct) {
        radius *= pct;
   }
}
/**
 * Client
 */
class BridgePattern {
   public static void main(String[] args) {
       Shape[] shapes = new Shape[] {
           new CircleShape(1, 2, 3, new DrawingAPI1()),
           new CircleShape(5, 7, 11, new DrawingAPI2()),
       };

       for (Shape shape : shapes) {
           shape.resizeByPercentage(2.5);
           shape.draw();
       }
   }
}

It will output:

API1.circle at 1.000000:2.000000 radius 7.5000000
API2.circle at 5.000000:7.000000 radius 27.500000
Implementation in PHP
interface DrawingAPI {
    function drawCircle($dX, $dY, $dRadius);
}

class DrawingAPI1 implements DrawingAPI {

    public function drawCircle($dX, $dY, $dRadius) {
        echo "API1.circle at ".$dX.":".$dY." radius ".$dRadius."<br/>";
    }
}

class DrawingAPI2 implements DrawingAPI {

    public function drawCircle($dX, $dY, $dRadius) {
        echo "API2.circle at ".$dX.":".$dY." radius ".$dRadius."<br/>";
    }
}

abstract class Shape {

    protected $oDrawingAPI;

    public abstract function draw();
    public abstract function resizeByPercentage($dPct);

    protected function __construct(DrawingAPI $oDrawingAPI) {
        $this->oDrawingAPI = $oDrawingAPI;
    }
}

class CircleShape extends Shape {

    private $dX;
    private $dY;
    private $dRadius;

    public function __construct(
            $dX, $dY,
            $dRadius,
            DrawingAPI $oDrawingAPI
    ) {
        parent::__construct($oDrawingAPI);
        $this->dX = $dX;
        $this->dY = $dY;
        $this->dRadius = $dRadius;
    }

    public function draw() {
        $this->oDrawingAPI->drawCircle(
                $this->dX,
                $this->dY,
                $this->dRadius
        );
    }

    public function resizeByPercentage($dPct) {
        $this->dRadius *= $dPct;
    }
}

class Tester {

    public static function main()  {
        $aShapes = array(
            new CircleShape(1, 3, 7,  new DrawingAPI1()),
            new CircleShape(5, 7, 11, new DrawingAPI2()),
        );

        foreach ($aShapes as $shapes) {
            $shapes->resizeByPercentage(2.5);
            $shapes->draw();
        }
    }
}

Tester::main();

Output:

   API1.circle at 1:3 radius 17.5
   API2.circle at 5:7 radius 27.5
Implementation in C#

C#

The following C# program illustrates the "shape" example given above and will output:

API1.circle at 1:2 radius 7.5
API2.circle at 5:7 radius 27.5
 using System;
 
 /** "Implementor" */
 interface IDrawingAPI {
    void DrawCircle(double x, double y, double radius);
 }
 
 /** "ConcreteImplementor" 1/2 */
 class DrawingAPI1 : IDrawingAPI {
    public void DrawCircle(double x, double y, double radius)
    {
        System.Console.WriteLine("API1.circle at {0}:{1} radius {2}", x, y, radius);
    }
 }
 
 /** "ConcreteImplementor" 2/2 */
 class DrawingAPI2 : IDrawingAPI
 {
    public void DrawCircle(double x, double y, double radius)
    {
        System.Console.WriteLine("API2.circle at {0}:{1} radius {2}", x, y, radius);
    }
 }
 
 /** "Abstraction" */
 interface IShape {
    void Draw();                             // low-level (i.e. Implementation-specific)
    void ResizeByPercentage(double pct);     // high-level (i.e. Abstraction-specific)
 }
 
 /** "Refined Abstraction" */
 class CircleShape : IShape {
    private double x, y, radius;
    private IDrawingAPI drawingAPI;
    public CircleShape(double x, double y, double radius, IDrawingAPI drawingAPI)
    {
        this.x = x;  this.y = y;  this.radius = radius;
        this.drawingAPI = drawingAPI;
    }
    // low-level (i.e. Implementation-specific)
    public void Draw() { drawingAPI.DrawCircle(x, y, radius); }
    // high-level (i.e. Abstraction-specific)
    public void ResizeByPercentage(double pct) { radius *= pct; }
 }
 
 /** "Client" */
 class BridgePattern {
    public static void Main(string[] args) {
        IShape[] shapes = new IShape[2];
        shapes[0] = new CircleShape(1, 2, 3, new DrawingAPI1());
        shapes[1] = new CircleShape(5, 7, 11, new DrawingAPI2());
 
        foreach (IShape shape in shapes) {
            shape.ResizeByPercentage(2.5);
            shape.Draw();
        }
    }
 }

C# using generics

The following C# program illustrates the "shape" example given above and will output:

API1.circle at 1:2 radius 7.5
API2.circle at 5:7 radius 27.5
 using System;
 
 /** "Implementor" */
 interface IDrawingAPI {
    void DrawCircle(double x, double y, double radius);
 }
 
 /** "ConcreteImplementor" 1/2 */
 struct DrawingAPI1 : IDrawingAPI {
    public void DrawCircle(double x, double y, double radius)
    {
        System.Console.WriteLine("API1.circle at {0}:{1} radius {2}", x, y, radius);
    }
 }
 
 /** "ConcreteImplementor" 2/2 */
 struct DrawingAPI2 : IDrawingAPI
 {
    public void DrawCircle(double x, double y, double radius)
    {
        System.Console.WriteLine("API2.circle at {0}:{1} radius {2}", x, y, radius);
    }
 }
 
 /** "Abstraction" */
 interface IShape {
    void Draw();                             // low-level (i.e. Implementation-specific)
    void ResizeByPercentage(double pct);     // high-level (i.e. Abstraction-specific)
 }
 
 /** "Refined Abstraction" */
 class CircleShape<T> : IShape
    where T : struct, IDrawingAPI
 {
    private double x, y, radius;
    private IDrawingAPI drawingAPI = new T();
    public CircleShape(double x, double y, double radius)
    {
        this.x = x;  this.y = y;  this.radius = radius;
    }
    // low-level (i.e. Implementation-specific)
    public void Draw() { drawingAPI.DrawCircle(x, y, radius); }
    // high-level (i.e. Abstraction-specific)
    public void ResizeByPercentage(double pct) { radius *= pct; }
 }
 
 /** "Client" */
 class BridgePattern {
    public static void Main(string[] args) {
        IShape[] shapes = new IShape[2];
        shapes[0] = new CircleShape<DrawingAPI1>(1, 2, 3);
        shapes[1] = new CircleShape<DrawingAPI2>(5, 7, 11);
 
        foreach (IShape shape in shapes) {
            shape.ResizeByPercentage(2.5);
            shape.Draw();
        }
    }
 }
Implementation in Python

The following Python program illustrates the "shape" example given above and will output:

API1.circle at 1:2 7.5
API2.circle at 5:7 27.5
# Implementor
class DrawingAPI:
    def drawCircle(x, y, radius):
        pass


# ConcreteImplementor 1/2
class DrawingAPI1(DrawingAPI):
    def drawCircle(self, x, y, radius):
        print("API1.circle at %f:%f radius %f" % (x, y, radius))


# ConcreteImplementor 2/2
class DrawingAPI2(DrawingAPI):
    def drawCircle(self, x, y, radius):
        print("API2.circle at %f:%f radius %f" % (x, y, radius))


# Abstraction
class Shape:
    # low-level
    def draw(self):
        pass

    # high-level
    def resizeByPercentage(self, pct):
        pass


# Refined Abstraction
class CircleShape(Shape):
    def __init__(self, x, y, radius, drawingAPI):
        self.__x = x
        self.__y = y
        self.__radius = radius
        self.__drawingAPI = drawingAPI

    # low-level i.e. Implementation specific
    def draw(self):
        self.__drawingAPI.drawCircle(self.__x, self.__y, self.__radius)

    # high-level i.e. Abstraction specific
    def resizeByPercentage(self, pct):
        self.__radius *= pct


def main():
    shapes = [
        CircleShape(1, 2, 3, DrawingAPI1()),
        CircleShape(5, 7, 11, DrawingAPI2())
    ]

    for shape in shapes:
        shape.resizeByPercentage(2.5)
        shape.draw()


if __name__ == "__main__":
    main()
Implementation in Ruby

An example in Ruby.

class Abstraction
  def initialize(implementor)
    @implementor = implementor
  end

  def operation
    raise 'Implementor object does not respond to the operation method' unless @implementor.respond_to?(:operation)
    @implementor.operation
  end
end

class RefinedAbstraction < Abstraction
  def operation
    puts 'Starting operation... '
    super
  end
end

class Implementor
  def operation
    puts 'Doing necessary stuff'
  end
end

class ConcreteImplementorA < Implementor
  def operation
    super
    puts 'Doing additional stuff'
  end
end

class ConcreteImplementorB < Implementor
  def operation
    super
    puts 'Doing other additional stuff'
  end
end

normal_with_a = Abstraction.new(ConcreteImplementorA.new)
normal_with_a.operation
# Doing necessary stuff
# Doing additional stuff

normal_with_b = Abstraction.new(ConcreteImplementorB.new)
normal_with_b.operation
# Doing necessary stuff
# Doing other additional stuff

refined_with_a = RefinedAbstraction.new(ConcreteImplementorA.new)
refined_with_a.operation
# Starting operation...
# Doing necessary stuff
# Doing additional stuff

refined_with_b = RefinedAbstraction.new(ConcreteImplementorB.new)
refined_with_b.operation
# Starting operation...
# Doing necessary stuff
# Doing other additional stuff
Implementation in Scala

A Scala implementation of the Java drawing example with the same output.

  /** "Implementor" */
  trait DrawingAPI {
    def drawCircle(x:Double, y:Double, radius:Double)
  }
 
  /** "ConcreteImplementor" 1/2 */
  class DrawingAPI1 extends DrawingAPI {
    def drawCircle(x:Double, y:Double, radius:Double) {
      printf("API1.circle at %f:%f radius %f\n", x, y, radius)
    }
  }
 
  /** "ConcreteImplementor" 2/2 */
  class DrawingAPI2 extends DrawingAPI {
    def drawCircle(x:Double, y:Double, radius:Double) {
      printf("API2.circle at %f:%f radius %f\n", x, y, radius)
    }
  }
 
  /** "Abstraction" */
  trait Shape {
     def draw()                             // low-level
     def resizeByPercentage(pct:Double)     // high-level
  }
 
  /** "Refined Abstraction" */
  class CircleShape(var x:Double, var y:Double,
    var radius:Double, val drawingAPI:DrawingAPI) extends Shape {
   
    // low-level i.e. Implementation specific
    def draw() = drawingAPI.drawCircle(x, y, radius)
   
    // high-level i.e. Abstraction specific
    def resizeByPercentage(pct:Double) = radius *= pct
  }
 
  /** "Client" */
  val shapes = List(
    new CircleShape(1, 2, 3, new DrawingAPI1),
    new CircleShape(5, 7, 11, new DrawingAPI2)
  )
 
  shapes foreach { shape =>
    shape.resizeByPercentage(2.5)
    shape.draw()
  }
Implementation in D

An example in D.

import std.stdio;

/** "Implementor" */
interface DrawingAPI {
    void drawCircle(double x, double y, double radius);
}

/** "ConcreteImplementor" 1/2 */
class DrawingAPI1: DrawingAPI {
    void drawCircle(double x, double y, double radius) {
        writefln("\nAPI1.circle at %f:%f radius %f", x, y, radius);
    }
}

/** "ConcreteImplementor" 2/2 */
class DrawingAPI2: DrawingAPI {
    void drawCircle(double x, double y, double radius) {
        writefln("\nAPI2.circle at %f:%f radius %f", x, y, radius);
    }
}

/** "Abstraction" */
interface Shape {
    void draw(); // low-level
    void resizeByPercentage(double pct); // high-level
}

/** "Refined Abstraction" */
class CircleShape: Shape {
    this(double x, double y, double radius, DrawingAPI drawingAPI) {
        this.x = x;
        this.y = y;
        this.radius = radius;
        this.drawingAPI = drawingAPI;
    }

    // low-level i.e. Implementation specific
    void draw() {
        drawingAPI.drawCircle(x, y, radius);
    }
    // high-level i.e. Abstraction specific
    void resizeByPercentage(double pct) {
        radius *= pct;
    }
private:
    double x, y, radius;
    DrawingAPI drawingAPI;
}

int main(string[] argv) {
    auto api1 = new DrawingAPI1();
    auto api2 = new DrawingAPI2();

    auto c1 = new CircleShape(1, 2, 3, api1);
    auto c2 = new CircleShape(5, 7, 11, api2);

    Shape[4] shapes;
    shapes[0] = c1;
    shapes[1] = c2;

    shapes[0].resizeByPercentage(2.5);
    shapes[0].draw();
    shapes[1].resizeByPercentage(2.5);
    shapes[1].draw();

    return 0;
}
Implementation in Perl

This example in Perl uses the MooseX::Declare module.

# Implementor
role Drawing::API {
    requires 'draw_circle';
}

# Concrete Implementor 1
class Drawing::API::1 with Drawing::API {
    method draw_circle(Num $x, Num $y, Num $r) {
        printf "API1.circle at %f:%f radius %f\n", $x, $y, $r;
    }
}

# Concrete Implementor 2
class Drawing::API::2 with Drawing::API {
    method draw_circle(Num $x, Num $y, Num $r) {
        printf "API2.circle at %f:%f radius %f\n", $x, $y, $r;
    }
}

# Abstraction
role Shape {
    requires qw( draw resize );
}

# Refined Abstraction
class Shape::Circle with Shape {
    has $_  => ( is => 'rw', isa  => 'Any' ) for qw( x y r );
    has api => ( is => 'ro', does => 'Drawing::API' );

    method draw() {
        $self->api->draw_circle( $self->x, $self->y, $self->r );
    }

    method resize(Num $percentage) {
        $self->{r} *= $percentage;
    }
}

my @shapes = (
    Shape::Circle->new( x=>1, y=>2, r=>3,  api => Drawing::API::1->new ),
    Shape::Circle->new( x=>5, y=>7, r=>11, api => Drawing::API::2->new ),
)

$_->resize( 2.5 ) and $_->draw for @shapes;
Implementation in Delphi

The following Delphi program illustrates the "shape" example given above and will output:

API1.circle at 1:2 7.5
API2.circle at 5:7 27.5
program Bridge;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils;

type

  ///implementator
  TDrawingAPI = class abstract
    procedure DrawCircle(x, y, radius: double); virtual; abstract;
  end;

  //ConcreteImplementator 1
  TDrawingAPI1 = class(TDrawingAPI)
    procedure DrawCircle(x, y, radius: double); override;
  end;

 //ConcreteImplementator 2
  TDrawingAPI2 = class(TDrawingAPI)
    procedure DrawCircle(x, y, radius: double);override;
  end;

  //Abstraction
  TShape = class abstract
    procedure Draw();virtual; abstract;// low-level (i.e. Implementation-specific)
    procedure ResizeByPercentage(pct: double);virtual; abstract;// high-level (i.e. Abstraction-specific)
  end;

  //Refined Abstraction
  TCircleShape = class(TShape)
    strict private
      x, y, radius: double;
      drawingAPI: TDrawingAPI;
    public
      constructor Create(x, y, radius: double; drawingAPI: TDrawingAPI);
      procedure Draw;override;
      procedure ResizeByPercentage(pct: double);override;
  end;

{ TDeawingAPI1 }

procedure TDrawingAPI1.DrawCircle(x, y, radius: double);
begin
  WriteLn('API1.circle at '+FloatToStr(x)+' : '+FloatToStr(y)+' radius '+FloatToStr(radius));
end;

{ TDeawingAPI }

procedure TDrawingAPI2.DrawCircle(x, y, radius: double);
begin
  WriteLn('API2.circle at '+FloatToStr(x)+' : '+FloatToStr(y)+' radius '+FloatToStr(radius));
end;

{ TCircleShape }

constructor TCircleShape.Create(x, y, radius: double; drawingAPI: TDrawingAPI);
begin
  self.x := x;
  self.y := y;
  self.radius := radius;
  self.drawingAPI := drawingAPI;
end;

procedure TCircleShape.Draw;
begin
  drawingAPI.DrawCircle(x, y, radius);
end;

procedure TCircleShape.ResizeByPercentage(pct: double);
begin
  radius := radius * pct;
end;

var shapes: array of TShape;
    shape: TShape;
begin
  try
    { TODO -oUser -cConsole Main : Insert code here }
    SetLength(shapes, 2);
    shapes[0] := TCircleShape.Create(1, 2, 3, TDrawingAPI1.Create);
    shapes[1] := TCircleShape.Create(5, 7, 11, TDrawingAPI2.Create);

    for shape in shapes do
    begin
       shape.ResizeByPercentage(2.5);
       shape.Draw;
    end;

    WriteLn(#13#10+'Press any key to continue..');
    ReadLn;

    shapes[0].Free;
    shapes[1].Free;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.

Builder

The builder pattern is useful to avoid a huge list of constructors for a class. Let's imagine a class that store the mode of transport (of an employee for instance). Here is the constructor that takes a MetroLine object as parameter:

modeOfTransport(MetroLine)

Now we need a constructor for the one that uses the car, the bus or the train:

new modeOfTransport(MetroLine)

new modeOfTransport()
new modeOfTransport(BusLine)

new modeOfTransport(Train)

For some of them, we need to indicate a travel allowance:

new modeOfTransport(MetroLine)

new modeOfTransport(MetroLine, Integer)
new modeOfTransport()
new modeOfTransport(Integer)
new modeOfTransport(BusLine)
new modeOfTransport(BusLine, Integer)
new modeOfTransport(Train)

new modeOfTransport(Train, Integer)

We have employees that have several modes of transport to go to work. We realize that the list of constructors is coming to a mess. Each new parameter leads to an exponent duplication of constructors. If some parameters have the same type, it becomes very confusing. A solution to this issue would be to first build a fake object and then fill it calling methods on it:

new modeOfTransport(MetroLine)

modeOfTransport.setMetroLine(MetroLine)
modeOfTransport.setCarTravel()
modeOfTransport.setBusLine(BusLine)
modeOfTransport.setTrain(Train)

modeOfTransport.setTravelAllowance(Integer)

The list of methods is no more exponent but the state of the object may be inconsistent. A better solution would be to set all the parameters to an object of another class, a pre-constructor, and then pass this object to the constructor of ModeOfTransport:

modeOfTransportPreConstructor.setMetroLine(MetroLine)

modeOfTransportPreConstructor.setCarTravel()
modeOfTransportPreConstructor.setBusLine(BusLine)
modeOfTransportPreConstructor.setTrain(Train)
modeOfTransportPreConstructor.setTravelAllowance(Integer)

new modeOfTransport(ModeOfTransportPreConstructor)

This solution is even better. We only have a valid ModeOfTransport object. However, the ModeOfTransport constructor can be called with a half-filled pre-constructor. So the pre-constructor should be a builder and should have a method that returns the ModeOfTransport object. This method will only return an object if the builder has been correctly filled, otherwise it returns null:

modeOfTransportBuilder.setMetroLine(MetroLine)

modeOfTransportBuilder.setCarTravel()
modeOfTransportBuilder.setBusLine(BusLine)
modeOfTransportBuilder.setTrain(Train)
modeOfTransportBuilder.setTravelAllowance(Integer)

modeOfTransport := modeOfTransportBuilder.getResult()

So the solution is to use a builder class. Let's see the structure of the code on the UML class diagram:

 
Builder Structure
  • Builder: Abstract interface for creating objects (product).
  • Concrete Builder: Provides implementation for Builder. It is an object able to construct other objects. Constructs and assembles parts to build the objects.

The builder pattern can be used for objects that contain flat data (html code, SQL query, X.509 certificate...), that is to say data that can't be easily edited. This type of data can not be edited step by step and must be edited at once. The best way to construct such an object is to use a builder class.

Examples

In Java, the StringBuffer and StringBuilder classes follow the builder design pattern. They are used to build String objects.

Cost

You can easily decide to use it. At worst, the pattern is useless.

Creation

Starting from a plain old class with a public constructor, implementing the design pattern is not very expensive. You can create the builder class aside your code. Then you will have to remove the existing constructor calls to use the builder instead. The refactoring is hardly automatic.

Maintenance

This design pattern has only small drawbacks. It may lead to small redundancies between the class and the builder structures but the both class have usually different structures. However, it is expensive to evolve to an abstract factory.

Removal

The refactoring is hardly automatic. It should be done manually.

Advices

  • Put the builder term in the name of the builder class to indicate the use of the pattern to the other developers.
  • Build your builder class as a fluent interface. It would increase the pattern interest.
  • If the target class contains flat data, your builder class can be constructed as a Composite that implements the Interpreter pattern.

Implementations

Implementation in Java

Building a car.

/**
 * Can have GPS, trip computer and a various number of seaters. Can be a city car, a sport car or a cabriolet.
 */
public class Car {
  /**
   * The description of the car.
   */
  private String description = null;

  /**
   * Construct and return the car.
   * @param aDescription The description of the car.
   */
  public Car(String aDescription) {
      description = aDescription;
    }
 
  /**
   * Print the car.
   * @return A flat representation.
   */
  public String toString() {
      return description;
    }
}
/**
 *
 */
public class CarBuilder {
  /**
   * Sport car.
   */
  private static final int SPORT_CAR = 1;

  /**
   * City car.
   */
  private static final int CITY_CAR = 2;

  /**
   * Cabriolet.
   */
  private static final int CABRIOLET = 3;

  /**
   * The type of the car.
   */
  private int carType;

  /**
   * True if the car has a trip computer.
   */
  private boolean hasTripComputer;

  /**
   * True if the car has a GPS.
   */
  private boolean hasGPS;

  /**
   * The number of seaters the car may have.
   */
  private int seaterNumber;

  /**
   * Construct and return the car.
   * @return a Car with the right options.
   */
  public Car getResult() {
      return new Car((carType == CITY_CAR) ? "A city car" : ((carType == SPORT_CAR) ? "A sport car" : "A cabriolet")
        + " with " + seaterNumber + " seaters"
        + (hasTripComputer ? " with a trip computer" : "")
        + (hasGPS ? " with a GPS" : "")
        + ".");
    }

  /**
   * Tell the builder the number of seaters.
   * @param number the number of seaters the car may have.
   */
  public void setSeaters(int number) {
      seaterNumber = number;
    }

  /**
   * Make the builder remember that the car is a city car.
   */
  public void setCityCar() {
      carType = CITY_CAR;
    }

  /**
   * Make the builder remember that the car is a cabriolet.
   */
  public void setCabriolet() {
      carType = CABRIOLET;
    }

  /**
   * Make the builder remember that the car is a sport car.
   */
  public void setSportCar() {
      carType = SPORT_CAR;
    }

  /**
   * Make the builder remember that the car has a trip computer.
   */
  public void setTripComputer() {
      hasTripComputer = true;
    }

  /**
   * Make the builder remember that the car has not a trip computer.
   */
  public void unsetTripComputer() {
      hasTripComputer = false;
    }

  /**
   * Make the builder remember that the car has a global positioning system.
   */
  public void setGPS() {
      hasGPS = true;
    }

  /**
   * Make the builder remember that the car has not a global positioning system.
   */
  public void unsetGPS() {
      hasGPS = false;
    }
}
/**
 * Construct a CarBuilder called carBuilder and build a car.
 */
public class Director {
  public static void main(String[] args) {
    CarBuilder carBuilder = new CarBuilder();
    carBuilder.setSeaters(2);
    carBuilder.setSportCar();
    carBuilder.setTripComputer();
    carBuilder.unsetGPS();
    Car car = carBuilder.getResult();

    System.out.println(car);
  }
}

It will produce:

A sport car with 2 seaters with a trip computer.

Building a pizza.

 /** "Product" */
class Pizza {
 private String dough = "";
 private String sauce = "";
 private String topping = "";

 public void setDough(final String dough) {
  this.dough = dough;
 }

 public void setSauce(final String sauce) {
  this.sauce = sauce;
 }

 public void setTopping(final String topping) {
  this.topping = topping;
 }
}
 /** "Abstract Builder" */
abstract class PizzaBuilder {
 protected Pizza pizza;

 public abstract void buildDough();
 public abstract void buildSauce();
 public abstract void buildTopping();

 public void createNewPizzaProduct() {
  this.pizza = new Pizza();
 }

 public Pizza getPizza() {
  return this.pizza;
 }
}
 /** "ConcreteBuilder" */
class HawaiianPizzaBuilder extends PizzaBuilder {
 @Override public void buildDough() {
  this.pizza.setDough("cross");
 }

 @Override public void buildSauce() {
  this.pizza.setSauce("mild");
 }

 @Override public void buildTopping() {
  this.pizza.setTopping("ham+pineapple");
 }
}
 /** "ConcreteBuilder" */
class SpicyPizzaBuilder extends PizzaBuilder {
 @Override public void buildDough() {
  this.pizza.setDough("pan baked");
 }

 @Override public void buildSauce() {
  this.pizza.setSauce("hot");
 }

 @Override public void buildTopping() {
  this.pizza.setTopping("pepperoni+salami");
 }
}
 /** "Director" */
class Waiter {
 private PizzaBuilder pizzaBuilder;

 public void setPizzaBuilder(final PizzaBuilder pb) {
  this.pizzaBuilder = pb;
 }

 public Pizza getPizza() {
  return this.pizzaBuilder.getPizza();
 }

 public void constructPizza() {
  this.pizzaBuilder.createNewPizzaProduct();
  this.pizzaBuilder.buildDough();
  this.pizzaBuilder.buildSauce();
  this.pizzaBuilder.buildTopping();
 }
}
 /** A customer ordering a pizza. */
class BuilderExample {

 public static void main(final String[] args) {

  final Waiter waiter = new Waiter();

  final PizzaBuilder hawaiianPizzaBuilder = new HawaiianPizzaBuilder();
  final PizzaBuilder spicyPizzaBuilder = new SpicyPizzaBuilder();

  waiter.setPizzaBuilder(hawaiianPizzaBuilder);
  waiter.constructPizza();

  final Pizza pizza = waiter.getPizza();

  waiter.setPizzaBuilder(spicyPizzaBuilder);
  waiter.constructPizza();

  final Pizza anotherPizza = waiter.getPizza();
 }
}
Implementation in C#

The Director assembles a bicycle instance in the example above, delegating the construction to a separate builder object that has been given to the Director by the Client.

/// <summary>
/// Represents a product created by the builder.
/// </summary>
public class Bicycle
{
    public Bicycle(string make, string model, string colour, int height)
    {
        Make = make;
        Model = model;
        Colour = colour;
        Height = height;
    }

    public string Make { get; set; }
    public string Model { get; set; }
    public int Height { get; set; }
    public string Colour { get; set; }
}

/// <summary>
/// The builder abstraction.
/// </summary>
public interface IBicycleBuilder
{
    Bicycle GetResult();

    string Colour { get; set; }
    int Height { get; set; }
}

/// <summary>
/// Concrete builder implementation.
/// </summary>
public class GTBuilder : IBicycleBuilder
{
    public Bicycle GetResult()
    {
        return Height == 29 ? new Bicycle("GT", "Avalanche", Colour, Height) : null;        
    }

    public string Colour { get; set; }
    public int Height { get; set; }
}

/// <summary>
/// The director.
/// </summary>
public class MountainBikeBuildDirector
{
    private IBicycleBuilder _builder;

    public MountainBikeBuildDirector(IBicycleBuilder builder) 
    {
        _builder = builder;
    }

    public void Construct()
    {
        _builder.Colour = "Red";
        _builder.Height = 29;
    }

    public Bicycle GetResult()
	{
		return this._builder.GetResult();
	}
}

public class Client
{
    public void DoSomethingWithBicycles()
    {
        var director = new MountainBikeBuildDirector(new GTBuilder());
        // Director controls the stepwise creation of product and returns the result.
        director.Construct();
        Bicycle myMountainBike = director.GetResult();
    }
}

Another example:

using System;

namespace BuilderPattern
{
  // Builder - abstract interface for creating objects (the product, in this case)
  abstract class PizzaBuilder
  {
    protected Pizza pizza;

    public Pizza GetPizza()
    {
      return pizza;
    }

    public void CreateNewPizzaProduct()
    {
      pizza = new Pizza();
    }

    public abstract void BuildDough();
    public abstract void BuildSauce();
    public abstract void BuildTopping();
  }
  // Concrete Builder - provides implementation for Builder; an object able to construct other objects.
  // Constructs and assembles parts to build the objects
  class HawaiianPizzaBuilder : PizzaBuilder
  {
    public override void BuildDough()
    {
      pizza.dough = "cross";
    }

    public override void BuildSauce()
    {
      pizza.sauce = "mild";
    }

    public override void BuildTopping()
    {
      pizza.topping = "ham+pineapple";
    }
  }
  // Concrete Builder - provides implementation for Builder; an object able to construct other objects.
  // Constructs and assembles parts to build the objects
  class SpicyPizzaBuilder : PizzaBuilder
  {
    public override void BuildDough()
    {
      pizza.dough = "pan baked";
    }

    public override void BuildSauce()
    {
      pizza.sauce = "hot";
    }

    public override void BuildTopping()
    {
      pizza.topping = "pepperoni + salami";
    }
  }
 
  // Director - responsible for managing the correct sequence of object creation.
  // Receives a Concrete Builder as a parameter and executes the necessary operations on it.
  class Cook
  {
    private PizzaBuilder _pizzaBuilder;

    public void SetPizzaBuilder(PizzaBuilder pb)
    {
      _pizzaBuilder = pb;
    }

    public Pizza GetPizza()
    {
      return _pizzaBuilder.GetPizza();
    }

    public void ConstructPizza()
    {
      _pizzaBuilder.CreateNewPizzaProduct();
      _pizzaBuilder.BuildDough();
      _pizzaBuilder.BuildSauce();
      _pizzaBuilder.BuildTopping();
    }
  }

  // Product - The final object that will be created by the Director using Builder
  public class Pizza
  {
    public string dough = string.Empty;
    public string sauce = string.Empty;
    public string topping = string.Empty;
  }

  class Program
  {
    static void Main(string[] args)
    {
      PizzaBuilder hawaiianPizzaBuilder = new HawaiianPizzaBuilder();
      Cook cook = new Cook();
      cook.SetPizzaBuilder(hawaiianPizzaBuilder);
      cook.ConstructPizza();
      // create the product
      Pizza hawaiian = cook.GetPizza();

      PizzaBuilder spicyPizzaBuilder = new SpicyPizzaBuilder();
      cook.SetPizzaBuilder(spicyPizzaBuilder);
      cook.ConstructPizza();
      // create another product
      Pizza spicy = cook.GetPizza();
    }
  }

}
Implementation in C++

This C++11 implementation is based on the pre C++98 implementation in the book.

#include <iostream>

enum Direction {North, South, East, West};

class MapSite {
public:
  virtual void enter() = 0;
  virtual ~MapSite() = default;
};

class Room : public MapSite {
public:
  Room() :roomNumber(0) {}
  Room(int n) :roomNumber(n) {}
  void setSide(Direction d, MapSite* ms) {
    std::cout << "Room::setSide " << d << ' ' << ms << '\n';
  }
  virtual void enter() {}
  Room(const Room&) = delete; // rule of three
  Room& operator=(const Room&) = delete;
private:
  int roomNumber;
};

class Wall : public MapSite {
public:
  Wall() {}
  virtual void enter() {}
};

class Door : public MapSite {
public:
  Door(Room* r1 = nullptr, Room* r2 = nullptr)
    :room1(r1), room2(r2) {}
  virtual void enter() {}
  Door(const Door&) = delete; // rule of three
  Door& operator=(const Door&) = delete;
private:
  Room* room1;
  Room* room2;
};

class Maze {
public:
  void addRoom(Room* r) {
    std::cout << "Maze::addRoom " << r << '\n';
  }
  Room* roomNo(int) const {
    return nullptr;
  }
};

class MazeBuilder {
public:
  virtual ~MazeBuilder() = default;
  virtual void buildMaze() = 0;
  virtual void buildRoom(int room) = 0;
  virtual void buildDoor(int roomFrom, int roomTo) = 0;

  virtual Maze* getMaze() {
    return nullptr;
  }
protected:
  MazeBuilder() = default;
};

// If createMaze is passed an object that can create a new maze in its entirety using operations for adding rooms, doors, and walls to the maze it builds, then you can use inheritance to change parts of the maze or the way the maze is built. This is an example of the Builder (110) pattern.

class MazeGame {
public:
  Maze* createMaze(MazeBuilder& builder) {
    builder.buildMaze();
    builder.buildRoom(1);
    builder.buildRoom(2);
    builder.buildDoor(1, 2);
    return builder.getMaze();
  }
  Maze* CreateComplexMaze(MazeBuilder& builder) {
    builder.buildRoom(1);
    // ...
    builder.buildRoom(1001);
    return builder.getMaze();
  }
};

class StandardMazeBuilder : public MazeBuilder {
public:
  StandardMazeBuilder() :currentMaze(nullptr) {}
  virtual void buildMaze() {
    currentMaze = new Maze;
  }
  virtual void buildRoom(int n) {
    if (!currentMaze->roomNo(n)) {
      Room* room = new Room(n);
      currentMaze->addRoom(room);
      room->setSide(North, new Wall);
      room->setSide(South, new Wall);
      room->setSide(East, new Wall);
      room->setSide(West, new Wall);
    }
  }
  virtual void buildDoor(int n1, int n2) {
    Room* r1 = currentMaze->roomNo(n1);
    Room* r2 = currentMaze->roomNo(n2);
    Door* d = new Door(r1, r2);
    r1->setSide(commonWall(r1,r2), d);
    r2->setSide(commonWall(r2,r1), d);
  }
  virtual Maze* getMaze() {
    return currentMaze;
  }
  StandardMazeBuilder(const StandardMazeBuilder&) = delete; // rule of three
  StandardMazeBuilder& operator=(const StandardMazeBuilder&) = delete;
private:
  Direction commonWall(Room*, Room*) {
    return North;
  }
  Maze* currentMaze;
};

int main() {
  MazeGame game;
  StandardMazeBuilder builder;
  game.createMaze(builder);
  builder.getMaze();
}

The program output is like:

Maze::addRoom 0x2145ed0
Room::setSide 0 0x2146300
Room::setSide 1 0x2146320
Room::setSide 2 0x2146340
Room::setSide 3 0x2146360
Maze::addRoom 0x2146380
Room::setSide 0 0x21463a0
Room::setSide 1 0x21463c0
Room::setSide 2 0x21463e0
Room::setSide 3 0x2146400
Room::setSide 0 0x2146420
Room::setSide 0 0x2146420

Another example:

#include <string>
#include <iostream>
using namespace std;
 
// "Product"
class Pizza {
public:
        void dough(const string& dough) {
                dough_ = dough;
        }
 
        void sauce(const string& sauce) {
                sauce_ = sauce;
        }
 
        void topping(const string& topping) {
                topping_ = topping;
        }
 
        void open() const {
                cout << "Pizza with " << dough_ << " dough, " << sauce_ << " sauce and "
                        << topping_ << " topping. Mmm." << endl;
        }
 
private:
        string dough_;
        string sauce_;
        string topping_;
};
 
// "Abstract Builder"
class PizzaBuilder {
public:
       // Chinmay Mandal : This default constructor may not be required here
        PizzaBuilder()
        {
           // Chinmay Mandal : Wrong syntax
           // pizza_ = new Pizza;
        }
        const Pizza& pizza() {
                return pizza_;
        }
 
        virtual void buildDough() = 0;
        virtual void buildSauce() = 0;
        virtual void buildTopping() = 0;
 
protected:
        Pizza pizza_;
};
 
class HawaiianPizzaBuilder : public PizzaBuilder {
public:
        void buildDough() {
                pizza_.dough("cross");
        }
 
        void buildSauce() {
                pizza_.sauce("mild");
        }
 
        void buildTopping() {
                pizza_.topping("ham+pineapple");
        }
};
 
class SpicyPizzaBuilder : public PizzaBuilder {
public:
        void buildDough() {
                pizza_.dough("pan baked");
        }
 
        void buildSauce() {
                pizza_.sauce("hot");
        }
 
        void buildTopping() {
                pizza_.topping("pepperoni+salami");
        }
};
 
class Cook {
public:
        Cook()
                : pizzaBuilder_(NULL/*nullptr*/)//Chinmay Mandal : nullptr replaced with NULL.
        {       }
 
        ~Cook() {
                if (pizzaBuilder_)
                        delete pizzaBuilder_;
        }
 
        void pizzaBuilder(PizzaBuilder* pizzaBuilder) {
                if (pizzaBuilder_)
                        delete pizzaBuilder_;
 
                pizzaBuilder_ = pizzaBuilder;
        }
 
        const Pizza& getPizza() {
                return pizzaBuilder_->pizza();
        }
 
        void constructPizza() {
                pizzaBuilder_->buildDough();
                pizzaBuilder_->buildSauce();
                pizzaBuilder_->buildTopping();
        }
 
private:
        PizzaBuilder* pizzaBuilder_;
};
 
int main() {
        Cook cook;
        cook.pizzaBuilder(new HawaiianPizzaBuilder);
        cook.constructPizza();
 
        Pizza hawaiian = cook.getPizza();
        hawaiian.open();
 
        cook.pizzaBuilder(new SpicyPizzaBuilder);
        cook.constructPizza();
 
        Pizza spicy = cook.getPizza();
        spicy.open();
}
Implementation in PHP
<?php
/** "Product" */
class Pizza {

    protected $dough;
    protected $sauce;
    protected $topping;

    public function setDough($dough) {
        $this->dough = $dough;
    }

    public function setSauce($sauce) {
        $this->sauce = $sauce;
    }

    public function setTopping($topping) {
        $this->topping = $topping;
    }

    public function showIngredients() {
        echo "Dough   : ".$this->dough."<br/>";
        echo "Sauce   : ".$this->sauce."<br/>";
        echo "Topping : ".$this->topping."<br/>";
    }
}

/** "Abstract Builder" */
abstract class PizzaBuilder {

    protected $pizza;

    public function getPizza() {
        return $this->pizza;
    }

    public function createNewPizzaProduct() {
        $this->pizza = new Pizza();
    }

    public abstract function buildDough();
    public abstract function buildSauce();
    public abstract function buildTopping();
}

/** "ConcreteBuilder" */
class HawaiianPizzaBuilder extends PizzaBuilder {
    public function buildDough() {
        $this->pizza->setDough("cross");
    }

    public function buildSauce() {
        $this->pizza->setSauce("mild");
    }

    public function buildTopping() {
        $this->pizza->setTopping("ham + pineapple");
    }
}

/** "ConcreteBuilder" */
class SpicyPizzaBuilder extends PizzaBuilder {

    public function buildDough() {
        $this->pizza->setDough("pan baked");
    }

    public function buildSauce() {
        $this->pizza->setSauce("hot");
    }

    public function buildTopping() {
        $this->pizza->setTopping("pepperoni + salami");
    }
}

/** "Director" */
class Waiter {

    protected $pizzaBuilder;

    public function setPizzaBuilder(PizzaBuilder $pizzaBuilder) {
        $this->pizzaBuilder = $pizzaBuilder;
    }

    public function getPizza() {
        return $this->pizzaBuilder->getPizza();
    }

    public function constructPizza() {
        $this->pizzaBuilder->createNewPizzaProduct();
        $this->pizzaBuilder->buildDough();
        $this->pizzaBuilder->buildSauce();
        $this->pizzaBuilder->buildTopping();
    }
}

class Tester {

    public static function main() {

        $oWaiter               = new Waiter();
        $oHawaiianPizzaBuilder = new HawaiianPizzaBuilder();
        $oSpicyPizzaBuilder    = new SpicyPizzaBuilder();

        $oWaiter->setPizzaBuilder($oHawaiianPizzaBuilder);
        $oWaiter->constructPizza();

        $pizza = $oWaiter->getPizza();
        $pizza->showIngredients();

        echo "<br/>";

        $oWaiter->setPizzaBuilder($oSpicyPizzaBuilder);
        $oWaiter->constructPizza();

        $pizza = $oWaiter->getPizza();
        $pizza->showIngredients();
    }
}

Tester::main();

output :

   Dough : cross
   Sauce : mild
   Topping : ham + pineapple
   Dough : pan baked
   Sauce : hot
   Topping : pepperoni + salami
Implementation in Ruby
# Product
class Pizza
  attr_accessor :dough, :sauce, :topping
end

# Abstract Builder
class PizzaBuilder
  def get_pizza
    @pizza
  end

  def create_new_pizza_product
    @pizza = Pizza.new
  end

  def build_dough; end
  def build_sauce; end
  def build_topping; end

end

# ConcreteBuilder
class HawaiianPizzaBuilder < PizzaBuilder
  def build_dough
    @pizza.dough = 'cross'
  end
 
  def build_sauce
    @pizza.sauce = 'mild'
  end

  def build_topping
    @pizza.topping = 'ham+pineapple'
  end
end

# ConcreteBuilder
class SpicyPizzaBuilder < PizzaBuilder
  def build_dough
    @pizza.dough = 'pan baked'
  end

  def build_sauce
    @pizza.sauce = 'hot'
  end

  def build_topping
    @pizza.topping = 'pepperoni+salami'
  end
end

# Director
class Waiter
  attr_accessor :pizza_builder

  def get_pizza
    pizza_builder.get_pizza
  end

  def construct_pizza
    pizza_builder.create_new_pizza_product
    pizza_builder.build_dough
    pizza_builder.build_sauce
    pizza_builder.build_topping
  end
end
 
# A customer ordering a pizza.
class BuilderExample
  def main(args = [])
    waiter = Waiter.new
    hawaiian_pizza_builder = HawaiianPizzaBuilder.new
    spicy_pizza_builder = SpicyPizzaBuilder.new

    waiter.pizza_builder = hawaiian_pizza_builder
    waiter.construct_pizza

    pizza = waiter.get_pizza
  end
end

puts BuilderExample.new.main.inspect
Implementation in Python
class Animal:
    """
    Abstract Animal
    """
    legs = 0
    tail = False
    roar = ''

class Mutator:
    """
    Mutator
    """
    def mutate(self):
        self.animal = Animal()

class Cat(Mutator):
    """
    Cat
    """
    def create_legs(self):
        self.animal.legs = 4
 
    def create_tail(self):
        self.animal.tail = True

    def create_roar(self):
        self.animal.roar = 'meowww!'

class Dog(Mutator):
    """
    Dog
    """
    def create_legs(self):
        self.animal.legs = 4

    def create_tail(self):
        self.animal.tail = True

    def create_roar(self):
        self.animal.roar = 'woffff!'

class AnimalOwner:
    """
    Farm owner
    """
    __mutator = ''
    def set_animal(self, mutator):
        self.__mutator = mutator

    def create_an_animal_for_me(self):
        self.__mutator.mutate()
        self.__mutator.create_legs()
        self.__mutator.create_tail()
        self.__mutator.create_roar()

    def get_animal(self):
        return self.__mutator.animal

c = Cat()
d = Dog()
ao = AnimalOwner()
ao.set_animal(c)
ao.create_an_animal_for_me()
animal = ao.get_animal()
print(animal.roar)  # meowww!
Implementation in Delphi
program Builder;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.SysUtils;

type
(*Product - final object that will be created by Director using Builder*)
  TPizza = class
    fDough: string;
    fSauce: string;
    fTopping: string;
    procedure Open;
  end;

  (*Builder - abstract class as interface for creating  objects -> product in this case*)
  TPizzaBuilder = class abstract
  protected
    fPizza: TPizza;
    public
    function GetPizza: TPizza;
    procedure CreateNewPizzaProduct;
    procedure BuildDough; virtual; abstract;
    procedure BuildSauce; virtual; abstract;
    procedure BuildTopping; virtual; abstract;
  end;

  (*concrete builder - provides implementation for Builder *)
  (*an object able to construct other objects.*)
  THawaiianPizzaBuilder = class(TPizzaBuilder)
    public
      procedure BuildDough; override;
      procedure BuildSauce; override;
      procedure BuildTopping; override;
  end;

  (*concrete builder = provides implenentation for Builder*)
  (*an object able to construct other objects.*)
  TSpicyPizzaBuilder = class(TPizzaBuilder)
    public
      procedure BuildDough; override;
      procedure BuildSauce; override;
      procedure BuildTopping; override;
  end;

  (*Director - responsible for managing the correct sequence of object creation.*)
  (*Receives a Concrete Builder as a parameter and executes the necessary operations on it.*)
  TCook = class
  protected
    fPizzaBuilder: TPizzaBuilder;
    public
      procedure SetPizzaBuilder(pb: TPizzaBuilder);
      function GetPizza: TPizza;
      procedure ConstructPizza;
  end;

{ THawaiianPizzaBuilder }

procedure THawaiianPizzaBuilder.BuildDough;
begin
  fPizza.fDough:= 'cross';
end;

procedure THawaiianPizzaBuilder.BuildSauce;
begin
  fPizza.fSauce:= 'mild';
end;

procedure THawaiianPizzaBuilder.BuildTopping;
begin
  fPizza.fTopping:= 'ham + pineapple';
end;

{ TSpicyPizzaBuilder }

procedure TSpicyPizzaBuilder.BuildDough;
begin
  fPizza.fDough:= 'pan baked';
end;

procedure TSpicyPizzaBuilder.BuildSauce;
begin
  fPizza.fSauce:= 'hot';
end;

procedure TSpicyPizzaBuilder.BuildTopping;
begin
  fPizza.fTopping:= 'pepperoni + salami';
end;

{ TCook }

procedure TCook.ConstructPizza;
begin
  fPizzaBuilder.CreateNewPizzaProduct;
  fPizzaBuilder.BuildDough;
  fPizzaBuilder.BuildSauce;
  fPizzaBuilder.BuildTopping;
end;

function TCook.GetPizza: TPizza;
begin
  Result:= fPizzaBuilder.GetPizza;
end;

procedure TCook.SetPizzaBuilder(pb: TPizzaBuilder);
begin
   fPizzaBuilder:= pb;
end;

{ TPizzaBuilder }

procedure TPizzaBuilder.CreateNewPizzaProduct;
begin
  fPizza:= TPizza.Create;
end;

function TPizzaBuilder.GetPizza: TPizza;
begin
   Result:= fPizza;
end;

{ TPizza }

procedure TPizza.Open;
begin
  WriteLn('Pizza with: ' + fDough + ' dough, ' +
  fSauce +' souce and '+fTopping +' topping. Mmm.');
end;

var
  cook: TCook;
  hawaiian, spicy: TPizza;

begin
  try
    { TODO -oUser -cConsole Main : Insert code here }

    cook:= TCook.Create;
    cook.SetPizzaBuilder(THawaiianPizzaBuilder.Create);
    cook.ConstructPizza;

    WriteLn('(* create the product *)');

    hawaiian:= cook.GetPizza;
    hawaiian.Open;

    WriteLn(#13#10+'(* create another product *)');

    cook.SetPizzaBuilder(TSpicyPizzaBuilder.Create);
    cook.ConstructPizza;

    spicy:= cook.GetPizza;
    spicy.Open;

    WriteLn(#13#10+'Press any key to continue...');
    ReadLn;

    spicy.Free;
    hawaiian.Free;
    cook.Free;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.

Chain of responsibility

Various examples of the Chain of responsibility pattern.

Implementation in Java

Below is an example of this pattern in Java. A logger is created using a chain of loggers, each one configured with different log levels.

import java.util.Arrays;
import java.util.EnumSet;
import java.util.function.Consumer;

@FunctionalInterface
public interface Logger {
    public enum LogLevel {
        INFO, DEBUG, WARNING, ERROR, FUNCTIONAL_MESSAGE, FUNCTIONAL_ERROR;

        public static LogLevel[] all() {
            return values();
        }
    }

    abstract void message(String msg, LogLevel severity);

    default Logger appendNext(Logger nextLogger) {
        return (msg, severity) -> {
            message(msg, severity);
            nextLogger.message(msg, severity);
        };
    }

    static Logger writeLogger(LogLevel[] levels, Consumer<String> stringConsumer) {
        EnumSet<LogLevel> set = EnumSet.copyOf(Arrays.asList(levels));
        return (msg, severity) -> {
            if (set.contains(severity)) {
                stringConsumer.accept(msg);
            }
        };
    }

    static Logger consoleLogger(LogLevel... levels) {
        return writeLogger(levels, msg -> System.err.println("Writing to console: " + msg));
    }

    static Logger emailLogger(LogLevel... levels) {
        return writeLogger(levels, msg -> System.err.println("Sending via email: " + msg));
    }

    static Logger fileLogger(LogLevel... levels) {
        return writeLogger(levels, msg -> System.err.println("Writing to Log File: " + msg));
    }
}

class Runner {
    public static void main(String[] args) {
        // Build an immutable chain of responsibility
        Logger logger = consoleLogger(LogLevel.all())
                .appendNext(emailLogger(LogLevel.FUNCTIONAL_MESSAGE, LogLevel.FUNCTIONAL_ERROR))
                .appendNext(fileLogger(LogLevel.WARNING, LogLevel.ERROR));

        // Handled by consoleLogger since the console has a LogLevel of all
        logger.message("Entering function ProcessOrder().", LogLevel.DEBUG);
        logger.message("Order record retrieved.", LogLevel.INFO);

        // Handled by consoleLogger and emailLogger since emailLogger implements Functional_Error & Functional_Message
        logger.message("Unable to Process Order ORD1 Dated D1 For Customer C1.", LogLevel.FUNCTIONAL_ERROR);
        logger.message("Order Dispatched.", LogLevel.FUNCTIONAL_MESSAGE);

        // Handled by consoleLogger and fileLogger since fileLogger implements Warning & Error
        logger.message("Customer Address details missing in Branch DataBase.", LogLevel.WARNING);
        logger.message("Customer Address details missing in Organization DataBase.", LogLevel.ERROR);
    }
}

The following Java code illustrates the pattern with the example of a logging class. Each logging handler decides if any action is to be taken at this log level and then passes the message on to the next logging handler. Note that this example should not be seen as a recommendation on how to write logging classes.

Also, note that in a 'pure' implementation of the chain of responsibility pattern, a logger would not pass responsibility further down the chain after handling a message. In this example, a message will be passed down the chain whether it is handled or not.

abstract class Logger {

    public static final int ERR = 3;
    public static final int NOTICE = 5;
    public static final int DEBUG = 7;
    private int mask;

    // The next element in the chain of responsibility
    private Logger next;

    public Logger(int mask) {
        this.mask = mask;
    }

    public Logger setNext(Logger l) {
        next = l;
        return l;
    }

    public void message(String msg, int priority) {
        if (priority <= mask) {
            writeMessage(msg);
        }
        if (next != null) {
            next.message(msg, priority);
        }
    }
   
    abstract protected void writeMessage(String msg);

}
class StdoutLogger extends Logger {

    public StdoutLogger(int mask) {
        super(mask);
    }

    protected void writeMessage(String msg) {
        System.out.println("Writing to stdout: " + msg);
    }

}
class EmailLogger extends Logger {

    public EmailLogger(int mask) {
        super(mask);
    }

    protected void writeMessage(String msg) {
        System.out.println("Sending via email: " + msg);
    }

}
class StderrLogger extends Logger {

    public StderrLogger(int mask) {
        super(mask);
    }

    protected void writeMessage(String msg) {
        System.err.println("Sending to stderr: " + msg);
    }

}
public class ChainOfResponsibilityExample {

    public static void main(String[] args) {
        // Build the chain of responsibility
        Logger l,l1;
        l1 = l = new StdoutLogger(Logger.DEBUG);
        l1 = l1.setNext(new EmailLogger(Logger.NOTICE));
        l1 = l1.setNext(new StderrLogger(Logger.ERR));

        // Handled by StdoutLogger
        l.message("Entering function y.", Logger.DEBUG);

        // Handled by StdoutLogger and EmailLogger
        l.message("Step1 completed.", Logger.NOTICE);

        // Handled by all three loggers
        l.message("An error has occurred.", Logger.ERR);
    }

}

The output is:

  Writing to stdout:   Entering function y.
  Writing to stdout:   Step1 completed.
  Sending via e-mail:  Step1 completed.
  Writing to stdout:   An error has occurred.
  Sending via e-mail:  An error has occurred.
  Writing to stderr:   An error has occurred.

Below is another example of this pattern in Java. In this example we have different roles, each having a fix purchase power limit and a successor. Every time a user in a role receives a purchase request, when it's over his limit, he just passes that request to his successor.

The PurchasePower abstract class with the abstract method processRequest.

abstract class PurchasePower {

    protected double final base = 500;
    protected PurchasePower successor;

    public void setSuccessor(PurchasePower successor) {
        this.successor = successor;
    }

    abstract public void processRequest(PurchaseRequest request);

}

Four implementations of the abstract class above: Manager, Director, Vice President, President

class ManagerPPower extends PurchasePower {

    private double final ALLOWABLE = 10 * base;

    public void processRequest(PurchaseRequest request) {
        if(request.getAmount() < ALLOWABLE) {
            System.out.println("Manager will approve $"+ request.getAmount());
        }
        else if(successor != null) {
            successor.processRequest(request);
        }
    }

}
class DirectorPPower extends PurchasePower {

    private double final ALLOWABLE = 20 * base;

    public void processRequest(PurchaseRequest request) {
        if(request.getAmount() < ALLOWABLE) {
            System.out.println("Director will approve $"+ request.getAmount());
        }
        else if(successor != null) {
            successor.processRequest(request);
        }
    }

}
class VicePresidentPPower extends PurchasePower {

    private double final ALLOWABLE = 40 * base;

    public void processRequest(PurchaseRequest request) {
        if(request.getAmount() < ALLOWABLE) {
            System.out.println("Vice President will approve $" + request.getAmount());
        }
        else if(successor != null) {
            successor.processRequest(request);
        }
    }
}
class PresidentPPower extends PurchasePower {

    private double final ALLOWABLE = 60 * base;
   
    public void processRequest(PurchaseRequest request) {
        if(request.getAmount() < ALLOWABLE) {
            System.out.println("President will approve $" + request.getAmount());
        }
        else {
            System.out.println( "Your request for $" + request.getAmount() + " needs a board meeting!");
        }
    }

}

The PurchaseRequest class with its Getter methods which keeps the request data in this example.

class PurchaseRequest {
 
    private int number;
    private double amount;
    private String purpose;

    public PurchaseRequest(int number, double amount, String purpose) {
        this.number = number;
        this.amount = amount;
        this.purpose = purpose;
    }

    public double getAmount() {
        return amount;
    }
    public void setAmount(double amt)  {
        amount = amt;
    }
   
    public String getPurpose() {
        return purpose;
    }
    public void setPurpose(String reason) {
        purpose = reason;
    }

    public int getNumber(){
        return number;
    }
    public void setNumber(int num) {
        number = num;
    }

}

And here a usage example, the successors are set like this: Manager -> Director -> Vice President -> President

class CheckAuthority {

    public static void main(String[] args) {
        ManagerPPower manager = new ManagerPPower();
        DirectorPPower director = new DirectorPPower();
        VicePresidentPPower vp = new VicePresidentPPower();
        PresidentPPower president = new PresidentPPower();
        manager.setSuccessor(director);
        director.setSuccessor(vp);
        vp.setSuccessor(president);
       
        //enter ctrl+c to kill.
        try{
            while (true) {
                System.out.println("Enter the amount to check who should approve your expenditure.");
                System.out.print(">");
                double d = Double.parseDouble(new BufferedReader(new InputStreamReader(System.in)).readLine());
                manager.processRequest(new PurchaseRequest(0, d, "General"));
           }
        }
        catch(Exception e){
            System.exit(1);
        }  
    }

}
Implementation in Python
"""
Chain of responsibility pattern example.
"""
from abc import ABCMeta, abstractmethod
from enum import Enum, auto

class LogLevel(Enum):
    """ Log Levels Enum."""
    NONE = auto()
    INFO = auto()
    DEBUG = auto()
    WARNING = auto()
    ERROR = auto()
    FUNCTIONAL_MESSAGE = auto()
    FUNCTIONAL_ERROR = auto()
    ALL = auto()

class Logger:
    """Abstract handler in chain of responsibility pattern."""
    __metaclass__ = ABCMeta

    next = None

    def __init__(self, levels) -> None:
        """Initialize new logger.

        Arguments:
            levels (list[str]): List of log levels.
        """
        self.log_levels = []

        for level in levels:
            self.log_levels.append(level)

    def set_next(self, next_logger: Logger):
        """Set next responsible logger in the chain.

        Arguments:
            next_logger (Logger): Next responsible logger.
        Returns: Logger: Next responsible logger.
        """
        self.next = next_logger
        return self.next

    def message(self, msg: str, severity: LogLevel) -> None:
        """Message writer handler.

        Arguments:
            msg (str): Message string.
            severity (LogLevel): Severity of message as log level enum.
        """
        if LogLevel.ALL in self.log_levels or severity in self.log_levels:
            self.write_message(msg)

        if self.next is not None:
            self.next.message(msg, severity)

    @abstractmethod
    def write_message(self, msg: str) -> None:
        """Abstract method to write a message.

        Arguments:
            msg (str): Message string.
        Raises: NotImplementedError
        """
        raise NotImplementedError("You should implement this method.")

class ConsoleLogger(Logger):
    def write_message(self, msg: str) -> None:
        """Overrides parent's abstract method to write to console.

        Arguments:
            msg (str): Message string.
        """
        print("Writing to console:", msg)

class EmailLogger(Logger):
    def write_message(self, msg: str) -> None:
        """Overrides parent's abstract method to send an email.

        Arguments:
            msg (str): Message string.
        """
        print(f"Sending via email: {msg}")

class FileLogger(Logger):
    def write_message(self, msg: str) -> None:
        """Overrides parent's abstract method to write a file.

        Arguments:
            msg (str): Message string.
        """
        print(f"Writing to log file: {msg}")

def main():
    """Building the chain of responsibility."""
    logger = ConsoleLogger([LogLevel.ALL])
    email_logger = logger.set_next(
        EmailLogger([LogLevel.FUNCTIONAL_MESSAGE, LogLevel.FUNCTIONAL_ERROR])
    )
    # As we don't need to use file logger instance anywhere later
    # We will not set any value for it.
    email_logger.set_next(
        FileLogger([LogLevel.WARNING, LogLevel.ERROR])
    )

    # ConsoleLogger will handle this part of code since the message
    # has a log level of all
    logger.message("Entering function ProcessOrder().", LogLevel.DEBUG)
    logger.message("Order record retrieved.", LogLevel.INFO)

    # ConsoleLogger and FileLogger will handle this part since file logger
    # implements WARNING and ERROR
    logger.message(
        "Customer Address details missing in Branch DataBase.",
        LogLevel.WARNING
    )
    logger.message(
        "Customer Address details missing in Organization DataBase.",
        LogLevel.ERROR
    )

    # ConsoleLogger and EmailLogger will handle this part as they implement
    # functional error
    logger.message(
        "Unable to Process Order ORD1 Dated D1 for customer C1.",
        LogLevel.FUNCTIONAL_ERROR
    )
    logger.message("OrderDispatched.", LogLevel.FUNCTIONAL_MESSAGE)

if __name__ == "__main__":
    main()

Another example:

class Car:
    def __init__(self):
        self.name = None
        self.km = 11100
        self.fuel = 5
        self.oil = 5
 
def handle_fuel(car):
    if car.fuel < 10:
        print "added fuel"
        car.fuel = 100

def handle_km(car):
    if car.km > 10000:
        print "made a car test."
        car.km = 0

def handle_oil(car):
    if car.oil < 10:
        print "Added oil"
        car.oil = 100
 
class Garage:
    def __init__(self):
        self.handlers = []
 
    def add_handler(self, handler):
        self.handlers.append(handler)
 
    def handle_car(self, car):
        for handler in self.handlers:
            handler(car)
 
if __name__ == '__main__':
    handlers = [handle_fuel, handle_km, handle_oil]
    garage = Garage()
 
    for handle in handlers:
        garage.add_handler(handle)
    garage.handle_car(Car())
Implementation in Crystal
enum LogLevel
  None
  Info
  Debug
  Warning
  Error
  FunctionalMessage
  FunctionalError
  All
end

abstract class Logger
  property log_levels
  property next : Logger | Nil

  def initialize(*levels)
    @log_levels = [] of LogLevel

    levels.each do |level|
      @log_levels << level
    end
  end

  def message(msg : String, severity : LogLevel)
    if @log_levels.includes?(LogLevel::All) || @log_levels.includes?(severity)
      write_message(msg)
    end
    @next.try(&.message(msg, severity))
  end

  abstract def write_message(msg : String)
end

class ConsoleLogger < Logger
  def write_message(msg : String)
    puts "Writing to console: #{msg}"
  end
end

class EmailLogger < Logger
  def write_message(msg : String)
    puts "Sending via email: #{msg}"
  end
end

class FileLogger < Logger
  def write_message(msg : String)
    puts "Writing to Log File: #{msg}"
  end
end

# Program
# Build the chain of responsibility
logger = ConsoleLogger.new(LogLevel::All)
logger1 = logger.next = EmailLogger.new(LogLevel::FunctionalMessage, LogLevel::FunctionalError)
logger2 = logger1.next = FileLogger.new(LogLevel::Warning, LogLevel::Error)

# Handled by ConsoleLogger since the console has a loglevel of all
logger.message("Entering function ProcessOrder().", LogLevel::Debug)
logger.message("Order record retrieved.", LogLevel::Info)

# Handled by ConsoleLogger and FileLogger since filelogger implements Warning & Error
logger.message("Customer Address details missing in Branch DataBase.", LogLevel::Warning)
logger.message("Customer Address details missing in Organization DataBase.", LogLevel::Error)

# Handled by ConsoleLogger and EmailLogger as it implements functional error
logger.message("Unable to Process Order ORD1 Dated D1 For Customer C1.", LogLevel::FunctionalError)

# Handled by ConsoleLogger and EmailLogger
logger.message("Order Dispatched.", LogLevel::FunctionalMessage)

Output

Writing to console: Entering function ProcessOrder().
Writing to console: Order record retrieved.
Writing to console: Customer Address details missing in Branch DataBase.
Writing to Log File: Customer Address details missing in Branch DataBase.
Writing to console: Customer Address details missing in Organization DataBase.
Writing to Log File: Customer Address details missing in Organization DataBase.
Writing to console: Unable to Process Order ORD1 Dated D1 For Customer C1.
Sending via email: Unable to Process Order ORD1 Dated D1 For Customer C1.
Writing to console: Order Dispatched.
Sending via email: Order Dispatched.
Implementation in PHP
<?php

abstract class Logger
{

    /**
     * Bitmask flags for severity.
     */
    public const NONE = 0;
    public const INFO = 0b000001;
    public const DEBUG = 0b000010;
    public const WARNING = 0b000100;
    public const ERROR = 0b001000;
    public const FUNCTIONAL_MESSAGE = 0b010000;
    public const FUNCTIONAL_ERROR = 0b100000;
    public const ALL = 0b111111;

    /** @var int A bitmask flag from this class. */
    protected int $logMask;

    /** @var \Logger|null An optional next logger to handle the message */
    protected ?Logger $next = null;

    /**
     * Logger constructor.
     *
     * @param int $mask
     *   A bitmask flag from this class.
     */
    public function __construct(int $mask)
    {
        $this->logMask = $mask;
    }

    /**
     * Set next responsible logger in the chain.
     *
     * @param \Logger $nextLogger
     *   Next responsible logger.
     *
     * @return \Logger
     *    Logger: Next responsible logger.
     */
    public function setNext(Logger $nextLogger): Logger
    {
        $this->next = $nextLogger;

        return $nextLogger;
    }

    /**
     * Message writer handler.
     *
     * @param string $msg
     *   Message string.
     * @param int $severity
     *   Severity of message as a bitmask flag from this class.
     *
     * @return $this
     */
    public function message(string $msg, int $severity): Logger
    {
        if ($severity & $this->logMask) {
            $this->writeMessage($msg);
        }
        if ($this->next !== null) {
            $this->next->message($msg, $severity);
        }

        return $this;
    }

    /**
     * Abstract method to write a message
     *
     * @param string $msg
     *   Message string.
     */
    abstract protected function writeMessage(string $msg): void;

}

class ConsoleLogger extends Logger
{

    protected function writeMessage(string $msg): void
    {
        echo "Writing to console: $msg\n";
    }

}

class EmailLogger extends Logger
{

    protected function writeMessage(string $msg): void
    {
        echo "Sending via email: $msg\n";
    }

}

class FileLogger extends Logger
{

    protected function writeMessage(string $msg): void
    {
        echo "Writing to a log file: $msg\n";
    }

}

$logger = new ConsoleLogger(Logger::ALL);
$logger
    ->setNext(new EmailLogger(Logger::FUNCTIONAL_MESSAGE | Logger::FUNCTIONAL_ERROR))
    ->setNext(new FileLogger(Logger::WARNING | Logger::ERROR));

$logger
    // Handled by ConsoleLogger since the console has a loglevel of all
    ->message("Entering function ProcessOrder().", Logger::DEBUG)
    ->message("Order record retrieved.", Logger::INFO)
    // Handled by ConsoleLogger and FileLogger since filelogger implements Warning & Error
    ->message("Customer Address details missing in Branch DataBase.", Logger::WARNING)
    ->message("Customer Address details missing in Organization DataBase.", Logger::ERROR)
    // Handled by ConsoleLogger and EmailLogger as it implements functional error
    ->message("Unable to Process Order ORD1 Dated D1 For Customer C1.", Logger::FUNCTIONAL_ERROR)
    // Handled by ConsoleLogger and EmailLogger
    ->message("Order Dispatched.", Logger::FUNCTIONAL_MESSAGE);

/* Output
Writing to console: Entering function ProcessOrder().
Writing to console: Order record retrieved.
Writing to console: Customer Address details missing in Branch DataBase.
Writing to a log file: Customer Address details missing in Branch DataBase.
Writing to console: Customer Address details missing in Organization DataBase.
Writing to a log file: Customer Address details missing in Organization DataBase.
Writing to console: Unable to Process Order ORD1 Dated D1 For Customer C1.
Sending via email: Unable to Process Order ORD1 Dated D1 For Customer C1.
Writing to console: Order Dispatched.
Sending via email: Order Dispatched.
*/
Implementation in Racket
#lang racket

; Define an automobile structure
(struct auto (fuel km oil) #:mutable #:transparent)

; Create an instance of an automobile
(define the-auto (auto 5 1500 7))

; Define handlers

(define (handle-fuel auto)
  (when (< (auto-fuel auto) 10)
    (begin (set-auto-fuel! auto 10)
           (printf "set fuel\n"))))

(define (handle-km auto)
  (when (> (auto-km auto) 10000)
    (begin (set-auto-km! auto 0)
           (printf "made a car test\n"))))

(define (handle-oil auto)
  (when (< (auto-oil auto) 10)
    (begin (set-auto-oil! auto (+ (auto-oil auto) 5))
           (printf "added oil\n"))))

; Apply each handler to the auto
(define (handle-auto handlers auto)
  (unless (null? handlers)
    (begin ((car handlers) auto)
           (handle-auto (cdr handlers) auto))))

(display the-auto)
(newline)

; Handle the auto
(handle-auto (list handle-fuel handle-km handle-oil) the-auto)

(display the-auto)
(newline)
Implementation in Perl

Java example about purchase power of various roles, using perl 5.10 and Moose.

use feature ':5.10';

package PurchasePower;
use Moose;

has successor => ( is => "rw", isa => "PurchasePower" );

sub processRequest {
    my ( $self, $req ) = @_;
    if ( $req->amount < $self->allowable ) {
        printf "%s will approve \$%.2f\n", $self->title, $req->amount;
    }
    elsif ( $self->successor ) {
        $self->successor->processRequest($req);
    }
    else {
        $self->no_match( $req );
    }
}

package ManagerPPower;
use Moose; extends "PurchasePower";
sub allowable {5000}
sub title     {"manager"}

package DirectorPPower;
use Moose; extends "PurchasePower";
sub allowable {10000}
sub title     {"director"}

package VicePresidentPPower;
use Moose; extends "PurchasePower";
sub allowable {20000}
sub title     {"vice-president"}

package PresidentPPower;
use Moose; extends "PurchasePower";
sub allowable {30000}
sub title     {"president"}

sub no_match {
    my ( $self, $req ) = @_;
    printf "your request for \$%.2f will need a board meeting\n", $req->amount;
}

package PurchaseRequest;
use Moose;

has number  => ( is => "rw", isa => "Int" );
has amount  => ( is => "rw", isa => "Num" );
has purpose => ( is => "rw", isa => "Str" );

package main;

my $manager   = new ManagerPPower;
my $director  = new DirectorPPower;
my $vp        = new VicePresidentPPower;
my $president = new PresidentPPower;

$manager->successor($director);
$director->successor($vp);
$vp->successor($president);

print "Enter the amount to check who should approve your expenditure.\n>";
my $amount = readline;
$manager->processRequest(
    PurchaseRequest->new(
        number  => 0,
        amount  => $amount,
        purpose => "General"
    )
);

Perl example using perl 5.10 and Moose.

use feature ':5.10';

package Car;
use Moose;

has name => ( is => "rw", default => undef );
has km   => ( is => "rw", default => 11100 );
has fuel => ( is => "rw", default => 5 );
has oil  => ( is => "rw", default => 5 );

sub handle_fuel {
    my $self = shift;
    if ( $self->fuel < 10 ) {
        say "added fuel";
        $self->fuel(100);
    }
}

sub handle_km {
    my $self = shift;
    if ( $self->km > 10000 ) {
        say "made a car test";
        $self->km(0);
    }
}

sub handle_oil {
    my $self = shift;
    if ( $self->oil < 10 ) {
        say "added oil";
        $self->oil(100);
    }
}

package Garage;
use Moose;

has handler => (
    is      => "ro",
    isa     => "ArrayRef[Str]",
    traits  => ['Array'],
    handles => { add_handler => "push", handlers => "elements" },
    default => sub { [] }
);

sub handle_car {
    my ($self, $car) = @_;
    $car->$_ for $self->handlers
}

package main;

my @handlers = qw( handle_fuel handle_km handle_oil );
my $garage   = Garage->new;
$garage->add_handler($_) for @handlers;
$garage->handle_car( Car->new );
Implementation in C#

This C# examples uses the logger application to select different sources based on the log level;

namespace ChainOfResponsibility;

[Flags]
public enum LogLevel
{
    None = 0,                 //        0
    Info = 1,                 //        1
    Debug = 2,                //       10
    Warning = 4,              //      100
    Error = 8,                //     1000
    FunctionalMessage = 16,   //    10000
    FunctionalError = 32,     //   100000
    All = 63                  //   111111
}

/// <summary>
/// Abstract Handler in chain of responsibility pattern.
/// </summary>
public abstract class Logger
{
    protected LogLevel logMask;

    // The next Handler in the chain
    protected Logger next;

    public Logger(LogLevel mask)
    {
        this.logMask = mask;
    }

    /// <summary>
    /// Sets the Next logger to make a list/chain of Handlers.
    /// </summary>
    public Logger SetNext(Logger nextlogger)
    {
        Logger lastLogger = this;

        while (lastLogger.next != null)
        {
            lastLogger = lastLogger.next;
        }

        lastLogger.next = nextlogger;
        return this;
    }

    public void Message(string msg, LogLevel severity)
    {
        if ((severity & logMask) != 0) // True only if any of the logMask bits are set in severity
        {
            WriteMessage(msg);
        }
        if (next != null) 
        {
            next.Message(msg, severity); 
        }
    }

    abstract protected void WriteMessage(string msg);
}

public class ConsoleLogger : Logger
{
    public ConsoleLogger(LogLevel mask)
        : base(mask)
    { }

    protected override void WriteMessage(string msg)
    {
        Console.WriteLine("Writing to console: " + msg);
    }
}

public class EmailLogger : Logger
{
    public EmailLogger(LogLevel mask)
        : base(mask)
    { }

    protected override void WriteMessage(string msg)
    {
        // Placeholder for mail send logic, usually the email configurations are saved in config file.
        Console.WriteLine("Sending via email: " + msg);
    }
}

class FileLogger : Logger
{
    public FileLogger(LogLevel mask)
        : base(mask)
    { }

    protected override void WriteMessage(string msg)
    {
        // Placeholder for File writing logic
        Console.WriteLine("Writing to Log File: " + msg);
    }
}

public class Program
{
    public static void Main(string[] args)
    {
        // Build the chain of responsibility
        Logger logger;
        logger = new ConsoleLogger(LogLevel.All)
                         .SetNext(new EmailLogger(LogLevel.FunctionalMessage | LogLevel.FunctionalError))
                         .SetNext(new FileLogger(LogLevel.Warning | LogLevel.Error));

        // Handled by ConsoleLogger since the console has a loglevel of all
        logger.Message("Entering function ProcessOrder().", LogLevel.Debug);
        logger.Message("Order record retrieved.", LogLevel.Info);

        // Handled by ConsoleLogger and FileLogger since filelogger implements Warning & Error
        logger.Message("Customer Address details missing in Branch DataBase.", LogLevel.Warning);
        logger.Message("Customer Address details missing in Organization DataBase.", LogLevel.Error);

        // Handled by ConsoleLogger and EmailLogger as it implements functional error
        logger.Message("Unable to Process Order ORD1 Dated D1 For Customer C1.", LogLevel.FunctionalError);

        // Handled by ConsoleLogger and EmailLogger
        logger.Message("Order Dispatched.", LogLevel.FunctionalMessage);
    }
}
 
/* Output
Writing to console: Entering function ProcessOrder().
Writing to console: Order record retrieved.
Writing to console: Customer Address details missing in Branch DataBase.
Writing to Log File: Customer Address details missing in Branch DataBase.
Writing to console: Customer Address details missing in Organization DataBase.
Writing to Log File: Customer Address details missing in Organization DataBase.
Writing to console: Unable to Process Order ORD1 Dated D1 For Customer C1.
Sending via email: Unable to Process Order ORD1 Dated D1 For Customer C1.
Writing to console: Order Dispatched.
Sending via email: Order Dispatched.
*/

Another example:

using System;

  class MainApp
  {
    static void Main()
    {
      // Setup Chain of Responsibility
      Handler h1 = new ConcreteHandler1();
      Handler h2 = new ConcreteHandler2();
      Handler h3 = new ConcreteHandler3();
      h1.SetSuccessor(h2);
      h2.SetSuccessor(h3);

      // Generate and process request
      int[] requests = {2, 5, 14, 22, 18, 3, 27, 20};

      foreach (int request in requests)
      {
        h1.HandleRequest(request);
      }

      // Wait for user
      Console.Read();
    }
  }

  // "Handler"
  abstract class Handler
  {
    protected Handler successor;

    public void SetSuccessor(Handler successor)
    {
      this.successor = successor;
    }

    public abstract void HandleRequest(int request);
  }

  // "ConcreteHandler1"
  class ConcreteHandler1 : Handler
  {
    public override void HandleRequest(int request)
    {
      if (request >= 0 && request < 10)
      {
        Console.WriteLine("{0} handled request {1}",
          this.GetType().Name, request);
      }
      else if (successor != null)
      {
        successor.HandleRequest(request);
      }
    }
  }

  // "ConcreteHandler2"
  class ConcreteHandler2 : Handler
  {
    public override void HandleRequest(int request)
    {
      if (request >= 10 && request < 20)
      {
        Console.WriteLine("{0} handled request {1}",
          this.GetType().Name, request);
      }
      else if (successor != null)
      {
        successor.HandleRequest(request);
      }
    }
  }

  // "ConcreteHandler3"
  class ConcreteHandler3 : Handler
  {
    public override void HandleRequest(int request)
    {
      if (request >= 20 && request < 30)
      {
        Console.WriteLine("{0} handled request {1}",
          this.GetType().Name, request);
      }
      else if (successor != null)
      {
        successor.HandleRequest(request);
      }
    }
  }

Command

The command pattern is an object behavioural pattern that decouples sender and receiver. It can also be thought as an object-oriented equivalent of a call back method. Call back: It is a function that is registered to be called at a later point of time based on user actions.

Scope

Object

Purpose

Behavioral

Intent

Encapsulate the request for a service as an object.

Applicability

  • to parameterize objects with an action to perform
  • to specify, queue, and execute requests at different times
  • for a history of requests
  • for multilevel undo/redo

Structure

 
UML diagram of the command pattern

Consequences

  • + abstracts executor of a service
  • + supports arbitrary-level undo-redo
  • + composition yields macro-commands
  • - might result in lots of trivial command subclasses

Examples

 

The best example for this pattern is the graphical user interface. On most multidata interfaces, you have both a "New" menu and a "New" button with an icon like in Libre Office Writer. Both controls are connected to a command object, so the action is performed by the same code.

Cost

This pattern is dealing with the whole architecture of a program. It may have a substantial impact on the project.

Creation

If the code already exists, this pattern is very expensive.

Maintenance

This pattern is very expensive to maintain.

Removal

This pattern is very expensive to remove, too.

Advises

  • Use the Command term to indicate the use of the pattern to the other developers.

Implementations

Consider a "simple" switch. In this example we configure the Switch with two commands: to turn the light on and to turn the light off. A benefit of this particular implementation of the command pattern is that the switch can be used with any device, not just a light — the Switch in the following example turns a light on and off, but the Switch's constructor is able to accept any subclasses of Command for its two parameters. For example, you could configure the Switch to start an engine.

Implementation in Java
/* The Command interface */
public interface Command {
   void execute();
}
import java.util.List;
import java.util.ArrayList;
/* The Invoker class */
public class Switch {
   private List<Command> history = new ArrayList<Command>();
   public Switch() {
   }
   public void storeAndExecute(Command cmd) {
      this.history.add(cmd); // optional
      cmd.execute();        
   }
}
/* The Receiver class */
public class Light {
   public Light() {
   }
   public void turnOn() {
      System.out.println("The light is on");
   }
   public void turnOff() {
      System.out.println("The light is off");
   }
}
/* The Command for turning on the light - ConcreteCommand #1 */
public class FlipUpCommand implements Command {
   private Light theLight;
   public FlipUpCommand(Light light) {
      this.theLight = light;
   }
   public void execute(){
      theLight.turnOn();
   }
}
/* The Command for turning off the light - ConcreteCommand #2 */
public class FlipDownCommand implements Command {
   private Light theLight;
   public FlipDownCommand(Light light) {
      this.theLight = light;
   }
   public void execute() {
      theLight.turnOff();
   }
}
/* The test class or client */
public class PressSwitch {
   public static void main(String[] args){
      // Check number of arguments
      if (args.length != 1) {
         System.err.println("Argument \"ON\" or \"OFF\" is required.");
         System.exit(-1);
      }

      Light lamp = new Light();
      Command switchUp = new FlipUpCommand(lamp);
      Command switchDown = new FlipDownCommand(lamp);

      // See criticism of this model above:
      // The switch itself should not be aware of lamp details (switchUp, switchDown)
      // either directly or indirectly
      Switch mySwitch = new Switch();

      switch (args[0]) {
         case "ON":
            mySwitch.storeAndExecute(switchUp);
            break;
         case "OFF":
            mySwitch.storeAndExecute(switchDown);
            break;
         default:
            System.err.println("Argument \"ON\" or \"OFF\" is required.");
            System.exit(-1);
        }
   }
}

Operations

The implementations to do are:

  • copying a command before putting it on a history list
  • handling hysteresis
  • supporting transactions
 public interface Command {
   public int execute(int a, int b);
 }
 public class AddCommand implements Command {
   public int execute(int a, int b) {
      return a + b;
   }
 }
 public class MultCommand implements Command {
   public int execute(int a, int b) {
      return a * b;
   }
 }
 public class TestCommand {
   public static void main(String a[]) {
     Command add = new AddCommand();
     add.execute(1, 2); // returns 3
     Command multiply = new MultCommand();
     multiply.execute(2, 3); // returns 6
   }
 }

In the above example, it can be noted that the command pattern decouples the object that invokes the operation from the ones having the knowledge to perform it.

Command in Java

Menus and buttons provide a classic example of the need for the command pattern. When you add a menu to an application, you have to configure the menu with words that describe actions that the user can choose, such as Save and Open. Similarly for a button. You also have to configure the menu or button so that it can take action, calling a method in response to a user's click. However, JMenuItem or JButton class has no way of knowing what action to perform when an item or button is selected. In the following example we use the same Action for both a menu item and a button saving us from having to write the same code twice.

 Action actionOpen = new AbstractAction("Open...", iconOpen) {
      public void actionPerformed(ActionEvent e) {
       ...    // open a file
      }
 }
 
 JMenu mFile = new JMenu("File");
 JMenuItem item =  mFile.add(actionOpen);   // use the same action for both a menu item ...
 
 JToolBar m_toolBar = new JToolBar();
 JButton bOpen = new JButton(actionOpen);   // ... and a button
 m_toolBar.add(bOpen);

Java Swing applications commonly apply the Mediator pattern, registering a single object to receive all GUI events. This object mediates the interaction of the components and translates user input into commands for business domain objects.

Undo in Java

Swing provides for Undo/Redo functionality.

 import javax.swing.undo.*;
 
 UndoManager undoManager = new UndoManager();
 Action undoAction, redoAction;
 undoAction = new AbstractAction("Undo",    
     new ImageIcon("edit_undo.gif")) {
      public void actionPerformed(ActionEvent e) {
        try {
          undoManager.undo(); // undoManager.redo();
        }
        catch (CannotUndoException ex) {
          System.err.println("Unable to undo: " + ex);
        }
        updateUndo();
      }
    };
 // same for Redo
 
 protected void updateUndo() {
    if(undo.canUndo()) {
      undoAction.setEnabled(true);
      undoAction.putValue(Action.NAME, undo.getUndoPresentationName());
    } else {
      undoAction.setEnabled(false);
      undoAction.putValue(Action.NAME, "Undo");
    }
    if(undo.canRedo()) {
      redoAction.setEnabled(true);
      redoAction.putValue(Action.NAME, undo.getRedoPresentationName());
    } else {
      redoAction.setEnabled(false);
      redoAction.putValue(Action.NAME, "Redo");
    }
  }
Implementation in C#

Consider a "simple" switch. In this example we configure the Switch with two commands: to turn the light on and to turn the light off.

A benefit of this particular implementation of the command pattern is that the switch can be used with any device, not just a light. The Switch in the following C# implementation turns a light on and off, but the Switch's constructor is able to accept any subclasses of Command for its two parameters. For example, you could configure the Switch to start an engine.

using System;

namespace CommandPattern;

public interface ICommand
{
    void Execute();
}

/* The Invoker class */
public class Switch
{
    ICommand _closedCommand;
    ICommand _openedCommand;

    public Switch(ICommand closedCommand, ICommand openedCommand)
    {
        _closedCommand = closedCommand;
        _openedCommand = openedCommand;
    }

    // Close the circuit / power on
    public void Close()
    {
       _closedCommand.Execute();
    }

    // Open the circuit / power off
    public void Open()
    {
        _openedCommand.Execute();
    }
}

/* An interface that defines actions that the receiver can perform */
public interface ISwitchable
{
    void PowerOn();
    void PowerOff();
}

/* The Receiver class */
public class Light : ISwitchable
{
    public void PowerOn()
    {
        Console.WriteLine("The light is on");
    }

    public void PowerOff()
    {
        Console.WriteLine("The light is off");
    }
}

/* The Command for turning off the device - ConcreteCommand #1 */
public class CloseSwitchCommand : ICommand
{
    private ISwitchable _switchable;

    public CloseSwitchCommand(ISwitchable switchable)
    {
        _switchable = switchable;
    }

    public void Execute()
    {
        _switchable.PowerOff();
    }
}

/* The Command for turning on the device - ConcreteCommand #2 */
public class OpenSwitchCommand : ICommand
{
    private ISwitchable _switchable;

    public OpenSwitchCommand(ISwitchable switchable)
    {
        _switchable = switchable;
    }

    public void Execute()
    {
        _switchable.PowerOn();
    }
}

/* The test class or client */
internal class Program
{
    public static void Main(string[] arguments)
    {
        string argument = arguments.Length > 0 ? arguments[0].ToUpper() : null;

        ISwitchable lamp = new Light();

        // Pass reference to the lamp instance to each command
        ICommand switchClose = new CloseSwitchCommand(lamp);
        ICommand switchOpen = new OpenSwitchCommand(lamp);

        // Pass reference to instances of the Command objects to the switch
        Switch @switch = new Switch(switchClose, switchOpen);

        if (argument == "ON")
        {
            // Switch (the Invoker) will invoke Execute() on the command object.
            @switch.Open();
        }
        else if (argument == "OFF")
        {
            // Switch (the Invoker) will invoke the Execute() on the command object.
            @switch.Close();
        }
        else
        {
            Console.WriteLine("Argument \"ON\" or \"OFF\" is required.");
        }
    }
}

The following code is another implementation of command pattern in C#.

using System;
using System.Collections.Generic;
namespace CommandPattern
{
    public interface ICommand
    {
        void Execute();
    }
    /* The Invoker class */
    public class Switch
    {
        private List<ICommand> _commands = new List<ICommand>();
        public void StoreAndExecute(ICommand command)
        {
            _commands.Add(command);
            command.Execute();
        }
    }
    /* The Receiver class */
    public class Light
    {
        public void TurnOn()
        {
            Console.WriteLine("The light is on");
        }
        public void TurnOff()
        {
            Console.WriteLine("The light is off");
        }
    }
    /* The Command for turning on the light - ConcreteCommand #1 */
    public class FlipUpCommand : ICommand
    {
        private Light _light;
        public FlipUpCommand(Light light)
        {
            _light = light;
        }
        public void Execute()
        {
            _light.TurnOn();
        }
    }
    /* The Command for turning off the light - ConcreteCommand #2 */
    public class FlipDownCommand : ICommand
    {
        private Light _light;
        public FlipDownCommand(Light light)
        {
            _light = light;
        }
        public void Execute()
        {
            _light.TurnOff();
        }
    }
    /* The test class or client */
    internal class Program
    {
        public static void Main(string[] args)
        {
            Light lamp = new Light();
            ICommand switchUp = new FlipUpCommand(lamp);
            ICommand switchDown = new FlipDownCommand(lamp);
            Switch s = new Switch();
            string arg = args.Length > 0 ? args[0].ToUpper() : null;
            if (arg == "ON")
            {
                s.StoreAndExecute(switchUp);
            }
            else if (arg == "OFF")
            {
                s.StoreAndExecute(switchDown);
            }
            else
            {
                Console.WriteLine("Argument \"ON\" or \"OFF\" is required.");
            }
        }
    }
}
Implementation in Python

The following code is an implementation of command pattern in Python.

class Switch(object):
    """The INVOKER class"""
    def __init__(self, flip_up_cmd, flip_down_cmd):
        self.flip_up = flip_up_cmd
        self.flip_down = flip_down_cmd
class Light(object):
    """The RECEIVER class"""
    def turn_on(self):
        print "The light is on"
    def turn_off(self):
        print "The light is off"
class LightSwitch(object):
    """The CLIENT class"""
    def __init__(self):
        lamp = Light()
        self._switch = Switch(lamp.turn_on, lamp.turn_off)
    def switch(self, cmd):
        cmd = cmd.strip().upper()
        if cmd == "ON":
            self._switch.flip_up()
        elif cmd == "OFF":
            self._switch.flip_down()
        else:
            print 'Argument "ON" or "OFF" is required.'
# Execute if this file is run as a script and not imported as a module
if __name__ == "__main__":
    light_switch = LightSwitch()
    print "Switch ON test."
    light_switch.switch("ON")
    print "Switch OFF test."
    light_switch.switch("OFF")
    print "Invalid Command test."
    light_switch.switch("****")
Implementation in Scala
/* The Command interface */
trait Command {
   def execute()
}
 
/* The Invoker class */
class Switch {
   private var history: List[Command] = Nil
 
   def storeAndExecute(cmd: Command) {
      cmd.execute()
      this.history :+= cmd
   }
}
 
/* The Receiver class */
class Light {
   def turnOn() = println("The light is on")
   def turnOff() = println("The light is off")
}
 
/* The Command for turning on the light - ConcreteCommand #1 */
class FlipUpCommand(theLight: Light) extends Command {
   def execute() = theLight.turnOn()
}
 
/* The Command for turning off the light - ConcreteCommand #2 */
class FlipDownCommand(theLight: Light) extends Command {
   def execute() = theLight.turnOff()
}
 
/* The test class or client */
object PressSwitch {
   def main(args: Array[String]) {
      val lamp = new Light()
      val switchUp = new FlipUpCommand(lamp)
      val switchDown = new FlipDownCommand(lamp)
 
      val s = new Switch()
 
      try {
         args(0).toUpperCase match {
            case "ON" => s.storeAndExecute(switchUp)
            case "OFF" => s.storeAndExecute(switchDown)
            case _ => println("Argument \"ON\" or \"OFF\" is required.")
         }
      } catch {
         case e: Exception => println("Arguments required.")
      }
   }
}
Implementation in JavaScript

The following code is an implementation of command pattern in Javascript.

/* The Invoker function */
var Switch = function(){
    this.storeAndExecute = function(command){
        command.execute();
    }
}
/* The Receiver function */
var Light = function(){
    this.turnOn = function(){ console.log ('turn on')};
    this.turnOff = function(){ console.log ('turn off') };
}
/* The Command for turning on the light - ConcreteCommand #1 */
var FlipUpCommand = function(light){
    this.execute = light.turnOn;
}
/* The Command for turning off the light - ConcreteCommand #2 */
var FlipDownCommand = function(light){
    this.execute = light.turnOff;
}
var light = new Light();
var switchUp = new FlipUpCommand(light);
var switchDown = new FlipDownCommand(light);
var s = new Switch();
s.storeAndExecute(switchUp);
s.storeAndExecute(switchDown);
Implementation in Smalltalk
Object subclass: #Switch
  instanceVariableNames:
    ' flipUpCommand flipDownCommand '
  classVariableNames: ''
  poolDictionaries: ''
 
Object subclass: #Light
  instanceVariableNames: ''
  classVariableNames: ''
  poolDictionaries: ''
 
Object subclass: #PressSwitch
  instanceVariableNames: ''
  classVariableNames: ''
  poolDictionaries: ''
 
!Switch class methods !
upMessage: flipUpMessage downMessage: flipDownMessage
^self new upMessage: flipUpMessage downMessage: flipDownMessage; yourself.! !
!Switch methods !
upMessage: flipUpMessage downMessage: flipDownMessage
flipUpCommand := flipUpMessage.
flipDownCommand := flipDownMessage.!
flipDown
flipDownCommand perform.!
 
flipUp
flipUpCommand perform.! !
 
!Light methods !
turnOff
Transcript show: 'The light is off'; cr.!
   
turnOn
Transcript show: 'The light is on'; cr.! !
!PressSwitch class methods !
switch: state
" This is the test method "
| lamp switchUp switchDown switch |
lamp := Light new.
switchUp := Message receiver: lamp selector: #turnOn.
switchDown := Message receiver: lamp selector: #turnOff.
switch := Switch upMessage: switchUp downMessage: switchDown.
state = #on ifTrue: [ ^switch flipUp ].
state = #off ifTrue: [ ^switch flipDown ].
Transcript show: 'Argument #on or #off is required.'.
! !
Implementation in PHP

The following code is an implementation of command pattern in PHP.

<?php

interface Command
{

    public function execute();
}

/** The Invoker class */
class Switcher
{

    private $history = array();

    public function storeAndExecute(Command $cmd)
    {
        $this->history[] = $cmd;
        $cmd->execute();
    }

}

/** The Receiver class */
class Light
{

    public function turnOn()
    {
        echo("The light is on");
    }

    public function turnOff()
    {
        echo("The light is off");
    }

}

/** The Command for turning on the light - ConcreteCommand #1 */
 class FlipUpCommand implements Command {
   private $theLight;

   public function __construct(Light $light) {
      $this->theLight = $light;
   }

   public function execute() {
       $this->theLight->turnOn();
   }
}

/** The Command for turning off the light - ConcreteCommand #2 */
 class FlipDownCommand implements Command {
   private $theLight;

   public function __construct(Light $light) {
      $this->theLight = $light;
   }

   public function execute() {
       $this->theLight->turnOff();
   }
}

/* The test class or client */
 class PressSwitch {
   public static  function main(string $args){

      $lamp = new Light();
      $switchUp = new FlipUpCommand($lamp);
      $switchDown = new FlipDownCommand($lamp);

      $mySwitch = new Switcher();

      switch($args) {
         case 'ON':
            $mySwitch->storeAndExecute($switchUp);
            break;
         case 'OFF':
            $mySwitch->storeAndExecute($switchDown);
            break;
         default:
            echo("Argument \"ON\" or \"OFF\" is required.");
            break;
      }
   }
}

/*INPUT*/

PressSwitch::main('ON'). PHP_EOL;
PressSwitch::main('OFF'). PHP_EOL;

/*OUTPUT*/
//The light is on
//The light is off

Composite

The composite design pattern reduces the cost of an implementation that handles data represented as a tree. When an application does a process on a tree, usually the process has to handle the iteration on the components, the move on the tree and has to process the nodes and the leafs separately. All of this creates a big amount of code. Suppose that you have to handle a file system repository. Each folders can contain files or folders. To handle this, you have an array of items that can be file or folder. The files have a name and the folders are arrays. Now you have to implement a file search operation on the whole folder tree. The pseudo-code should look like this:

method searchFilesInFolders(rootFolder, searchedFileName) is
    input: a list of the content of the rootFolder.
    input: the searchedFileName that should be found in the folders.
    output: the list of encountered files.

  Empty the foundFiles list
  Empty the parentFolders list
  Empty the parentIndices list
  currentFolder := rootFolder
  currentIndex := 0
  Add rootFolder to parentFolders

  while parentFolders is not empty do
    if currentIndex is out of currentFolder then
        currentFolder := last item of parentFolders
        Remove the last item of parentFolders
        currentIndex := last item of parentIndices + 1
        Remove the last item of parentIndices

    else if the item at the currentIndex of the currentFolder is a folder then
      currentFolder := the folder
      Add currentFolder to parentFolders
      Add currentIndex to parentIndices
      currentIndex := 0

    otherwise
      if the name of the file is equal to the searchedFileName then
        Add the file to foundFiles
      Increment currentIndex

  Return the foundFiles

In the previous code, each iteration of the same while loop is a process of one node or leaf. At the end of the process, the code move to the position of the next node or leaf to process. There are three branches in the loop. The first branch is true when we have processed all the children of the node and it moves to the parent, the second goes into a child node and the last process a leaf (i.e. a file). The memory of the location should be stored to go back in the tree. The problem in this implementation is that it is hardly readable and the process of the folders and the files is completely separate. This code is heavy to maintain and you have to think to the whole tree each moment. The folders and the files should be called the same way so they should be objects that implements the same interface.

 
Composite pattern in UML.
Component
  • is the abstraction for all components, including composite ones.
  • declares the interface for objects in the composition.
  • (optional) defines an interface for accessing a component's parent in the recursive structure, and implements it if that's appropriate.
Leaf
  • represents leaf objects in the composition.
  • implements all Component methods.
Composite
  • represents a composite Component (component having children).
  • implements methods to manipulate children.
  • implements all Component methods, generally by delegating them to its children.

So now the implementation is rather like this:

interface FileSystemComponent is
  method searchFilesInFolders(searchedFileName) is
      input: the searchedFileName that should be found in the folders.
      output: the list of encountered files.
class File implementing FileSystemComponent is
  method searchFilesInFolders(searchedFileName) is
      input: the searchedFileName that should be found in the folders.
      output: the list of encountered files.

    if the name of the file is equal to the searchedFileName then
      Empty the foundFiles list
      Add the file to foundFiles
      Return the foundFiles

    otherwise
      Return an empty list
class Folder implementing FileSystemComponent is
  field children is
    The list of the direct children.

  method searchFilesInFolders(searchedFileName) is
      input: the searchedFileName that should be found in the folders.
      output: the list of encountered files.

    Empty the foundFiles list

    for each child in children
      Call searchFilesInFolders(searchedFileName) on the child
      Add the result to foundFiles

    Return the foundFiles

As you can see, a component can be an individual object and also can be a collection of objects. A Composite pattern can represent both the conditions. In this pattern, one can develop tree structures for representing part-whole hierarchies.

Examples

The best example of use of this pattern is the Graphical User Interface. The widgets of the interface are organized in a tree and the operations (resizing, repainting...) on all the widgets are processed using the composite design pattern.

Cost

This pattern is one of the least expensive patterns. You can implement it each time you have to handle a tree of data without worrying. There is no bad usage of this pattern. The cost of the pattern is only to handle the children of a composite but this cost would be required and more expensive without the design pattern.

Creation

You have to create an almost empty interface and implement the management of the composite children. This cost is very low.

Maintenance

You can't get caught in the system. The only relatively expensive situation occurs when you have to often change the operations applied to the whole data tree.

Removal

You should remove the pattern when you remove the data tree. So you just remove all in once. This cost is very low.

Advices

  • Put the composite and component terms in the name of the classes to indicate the use of the pattern to the other developers.

Implementations

Various examples of the composite pattern.

Implementation in C#
using System;
using System.Collections.Generic;
namespace Composite
{
    class Program
    {
        interface IGraphic
        {
            void Print();
        }
        class CompositeGraphic : IGraphic
        {
            private List<IGraphic> child = new List<IGraphic>();
            public CompositeGraphic(IEnumerable<IGraphic> collection)
            {
                child.AddRange(collection);
            }
            public void Print()
            {
                foreach(IGraphic g in child)
                {
                    g.Print();
                }
            }
        }
        class Ellipse : IGraphic
        {
            public void Print()
            {
                Console.WriteLine("Ellipse");
            }
        }
        static void Main(string[] args)
        {
            new CompositeGraphic(new IGraphic[]
                {
                    new CompositeGraphic(new IGraphic[]
                        {
                            new Ellipse(),
                            new Ellipse(),
                            new Ellipse()
                        }),
                    new CompositeGraphic(new IGraphic[]
                        {
                            new Ellipse()
                        })
                }).Print();
        }
    }
}
Implementation in Common Lisp

The following example, written in Common Lisp, and translated directly from the Java example below it, implements a method named print-graphic, which can be used on either an ellipse, or a list whose elements are either lists or ellipses.

(defstruct ellipse) ;; An empty struct.
;; For the method definitions, "object" is the variable,
;; and the following word is the type.
(defmethod print-graphic ((object null))
  NIL)
(defmethod print-graphic ((object cons))
  (print-graphic (first object))
  (print-graphic (rest object)))
(defmethod print-graphic ((object ellipse))
  (print 'ELLIPSE))
(let* ((ellipse-1 (make-ellipse))
       (ellipse-2 (make-ellipse))
       (ellipse-3 (make-ellipse))
       (ellipse-4 (make-ellipse)))
  (print-graphic (cons (list ellipse-1 (list ellipse-2 ellipse-3)) ellipse-4)))
Implementation in Java

The following example, written in Java, implements a graphic class, which can be either an ellipse or a composition of several graphics. Every graphic can be printed. In Backus-Naur form,

Graphic ::= ellipse | GraphicList
GraphicList ::= empty | Graphic GraphicList

It could be extended to implement several other shapes (rectangle, etc.) and methods (translate, etc.).

import java.util.List;
import java.util.ArrayList;

/** "Component" */
interface Graphic {
    //Prints the graphic.
    public void print();
}

/** "Composite" */
class CompositeGraphic implements Graphic {
    //Collection of child graphics.
    private final List<Graphic> childGraphics = new ArrayList<>();

    //Adds the graphic to the composition.
    public void add(Graphic graphic) {
        childGraphics.add(graphic);
    }
    
    //Prints the graphic.
    @Override
    public void print() {
        for (Graphic graphic : childGraphics) {
            graphic.print();  //Delegation
        }
    }
}

/** "Leaf" */
class Ellipse implements Graphic {
    //Prints the graphic.
    @Override
    public void print() {
        System.out.println("Ellipse");
    }
}

/** Client */
class CompositeDemo {
    public static void main(String[] args) {
        //Initialize four ellipses
        Ellipse ellipse1 = new Ellipse();
        Ellipse ellipse2 = new Ellipse();
        Ellipse ellipse3 = new Ellipse();
        Ellipse ellipse4 = new Ellipse();

        //Creates two composites containing the ellipses
        CompositeGraphic compositGraphic2 = new CompositeGraphic();
        compositGraphic2.add(ellipse1);
        compositGraphic2.add(ellipse2);
        compositGraphic2.add(ellipse3);
        
        CompositeGraphic compositGraphic3 = new CompositeGraphic();
        compositGraphic3.add(ellipse4);
        
        //Create another graphics that contains two graphics
        CompositeGraphic compositGraphic = new CompositeGraphic();
        compositGraphic.add(compositGraphic2);
        compositGraphic.add(compositGraphic3);

        //Prints the complete graphic (Four times the string "Ellipse").
        compositGraphic.print();
    }
}

The following example, written in Java, implements a graphic class, which can be either an ellipse or a composition of several graphics. Every graphic can be printed. In algebraic form,

       Graphic = ellipse | GraphicList
       GraphicList = empty | Graphic GraphicList

It could be extended to implement several other shapes (rectangle, etc.) and methods (translate, etc.).

/** "Component" */
interface Graphic {
    // Prints the graphic.
    public void print();
}
/** "Composite" */
import java.util.List;
import java.util.ArrayList;
class CompositeGraphic implements Graphic {
    // Collection of child graphics.
    private List<Graphic> mChildGraphics = new ArrayList<Graphic>();
    // Prints the graphic.
    public void print() {
        for (Graphic graphic : mChildGraphics) {
            graphic.print();
        }
    }
    // Adds the graphic to the composition.
    public void add(Graphic graphic) {
        mChildGraphics.add(graphic);
    }
    // Removes the graphic from the composition.
    public void remove(Graphic graphic) {
        mChildGraphics.remove(graphic);
    }
}
/** "Leaf" */
class Ellipse implements Graphic {
    // Prints the graphic.
    public void print() {
        System.out.println("Ellipse");
    }
}
/** Client */
public class Program {
    public static void main(String[] args) {
        // Initialize four ellipses
        Ellipse ellipse1 = new Ellipse();
        Ellipse ellipse2 = new Ellipse();
        Ellipse ellipse3 = new Ellipse();
        Ellipse ellipse4 = new Ellipse();
        // Initialize three composite graphics
        CompositeGraphic graphic = new CompositeGraphic();
        CompositeGraphic graphic1 = new CompositeGraphic();
        CompositeGraphic graphic2 = new CompositeGraphic();
        // Composes the graphics
        graphic1.add(ellipse1);
        graphic1.add(ellipse2);
        graphic1.add(ellipse3);
        graphic2.add(ellipse4);
        graphic.add(graphic1);
        graphic.add(graphic2);
        // Prints the complete graphic (four times the string "Ellipse").
        graphic.print();
    }
}
Implementation in PHP
<?php
/** "Component" */
interface Graphic
{
    /**
     * Prints the graphic
     *
     * @return void
     */
    public function printOut();
}
 
/**
 * "Composite" - Collection of graphical components
 */
class CompositeGraphic implements Graphic
{
    /**
     * Collection of child graphics
     *
     * @var array
     */
    private $childGraphics = array();
 
    /**
     * Prints the graphic
     *
     * @return void
     */
    public function printOut()
    {
        foreach ($this->childGraphics as $graphic) {
            $graphic->printOut();
        }
    }
 
    /**
     * Adds the graphic to the composition
     *
     * @param Graphic $graphic Graphical element
     *
     * @return void  
     */
    public function add(Graphic $graphic)
    {
        $this->childGraphics[] = $graphic;
    }
 
    /**
     * Removes the graphic from the composition
     *
     * @param Graphic $graphic Graphical element
     *
     * @return void
     */
    public function remove(Graphic $graphic)
    {
        if (in_array($graphic, $this->childGraphics)) {
            unset($this->childGraphics[array_search($graphic, $this->childGraphics)]);
        }
    }
}
 
/** "Leaf" */
class Ellipse implements Graphic
{
    /**
     * Prints the graphic
     *
     * @return void
     */
    public function printOut()
    {
        echo "Ellipse";
    }
}
 
/** Client */
 
//Initialize four ellipses
$ellipse1 = new Ellipse();
$ellipse2 = new Ellipse();
$ellipse3 = new Ellipse();
$ellipse4 = new Ellipse();
 
//Initialize three composite graphics
$graphic = new CompositeGraphic();
$graphic1 = new CompositeGraphic();
$graphic2 = new CompositeGraphic();
 
//Composes the graphics
$graphic1->add($ellipse1);
$graphic1->add($ellipse2);
$graphic1->add($ellipse3);
 
$graphic2->add($ellipse4);
 
$graphic->add($graphic1);
$graphic->add($graphic2);
 
//Prints the complete graphic (four times the string "Ellipse").
$graphic->printOut();
Implementation in Python
class Component(object):
    def __init__(self, *args, **kw):
        pass
    def component_function(self): pass
class Leaf(Component):
    def __init__(self, *args, **kw):
        Component.__init__(self, *args, **kw)
    def component_function(self):
        print "some function"
class Composite(Component):
    def __init__(self, *args, **kw):
        Component.__init__(self, *args, **kw)
        self.children = []
   
    def append_child(self, child):
        self.children.append(child)
   
    def remove_child(self, child):
        self.children.remove(child)
    def component_function(self):
        map(lambda x: x.component_function(), self.children)
   
c = Composite()
l = Leaf()
l_two = Leaf()
c.append_child(l)
c.append_child(l_two)
c.component_function()
Implementation in Ruby
module Component
  def do_something
    raise NotImplementedError
  end
end
class Leaf
  include Component
  def do_something
    puts "Hello"
  end
end
class Composite
  include Component
  attr_accessor :children
  def initialize
    self.children = []
  end
  def do_something
    children.each {|c| c.do_something}
  end
  def append_child(child)
    children << child
  end
  def remove_child(child)
    children.delete child
  end
end
composite = Composite.new
leaf_one = Leaf.new
leaf_two = Leaf.new
composite.append_child(leaf_one)
composite.append_child(leaf_two)
composite.do_something

Decorator

The decorator pattern helps to add behavior or responsibilities to an object. This is also called “Wrapper”.

Examples

Cost

This pattern can be very expensive. You should only use it when it is really necessary. You should have lots of different behaviors and responsibilities for the same class.

Creation

This pattern is expensive to create.

Maintenance

This pattern can be expensive to maintain. If the representation of a class often changes, you will have lots of refactoring.

Removal

This pattern is hard to remove too.

Advises

  • Put the decorator term in the name of the decorator classes to indicate the use of the pattern to the other developers.

Implementations

Implementation in C#

This example illustrates a simple extension method for a bool type.

using System;

// Extension methods must be parts of static classes.
static class BooleanExtensionMethodSample
{
    public static void Main()
    {
        bool yes = true;
        bool no = false;
        // Toggle the booleans! yes should return false and no should return true.
        Console.WriteLine(yes.Toggle());
        Console.WriteLine(no.Toggle());
    }
    // The extension method that adds Toggle to bool.
    public static bool Toggle(this bool target)
    {
        // Return the opposite of the target.
        return !target;
    }
}
Implementation in C++

Coffee making scenario

# include <iostream>
# include <string>
// The abstract coffee class
class Coffee
{
public:
    virtual double getCost() = 0;
    virtual std::string getIngredient() = 0;
    virtual ~Coffee() {}
};
// Plain coffee without ingredient
class SimpleCoffee:public Coffee
{
private:
    double cost;
    std::string ingredient;
public:
    SimpleCoffee()
    {
        cost = 1;
        ingredient = std::string("Coffee");
    }
    double getCost()
    {
        return cost;
    }
    std::string getIngredient()
    {
        return ingredient;
    }
};
// Abstract decorator class
class CoffeeDecorator:public Coffee
{
protected:
    Coffee & decoratedCoffee;
public:
    CoffeeDecorator(Coffee & decoratedCoffee):decoratedCoffee(decoratedCoffee){}
    ~CoffeeDecorator()  {
        delete &decoratedCoffee;
    }
};
// Milk Decorator
class Milk:public CoffeeDecorator
{
private:
    double cost;
public:
    Milk(Coffee & decoratedCoffee):CoffeeDecorator(decoratedCoffee)
    {
        cost = 0.5;
    }
    double getCost()
    {
        return cost + decoratedCoffee.getCost();
    }
    std::string getIngredient()
    {
        return "Milk "+decoratedCoffee.getIngredient();
    }
};
// Whip decorator
class Whip:public CoffeeDecorator
{
private:
    double cost;
public:
    Whip(Coffee & decoratedCoffee):CoffeeDecorator(decoratedCoffee)
    {
        cost = 0.7;
    }
    double getCost()
    {
        return cost + decoratedCoffee.getCost();
    }
    std::string getIngredient()
    {
        return "Whip "+decoratedCoffee.getIngredient();
    }
};
// Sprinkles decorator
class Sprinkles:public CoffeeDecorator
{
private:
    double cost;
public:
    Sprinkles(Coffee & decoratedCoffee):CoffeeDecorator(decoratedCoffee)
    {
        cost = 0.6;
    }
    double getCost()
    {
        return cost + decoratedCoffee.getCost();
    }
    std::string getIngredient()
    {
        return "Sprinkles "+decoratedCoffee.getIngredient();
    }
};
// Here's a test
int main()
{
    Coffee* sample;
    sample = new SimpleCoffee();
    sample = new Milk(*sample);
    sample = new Whip(*sample);
    std::cout << sample->getIngredient() << std::endl;
    std::cout << "Cost: " << sample->getCost() << std::endl;
    delete sample;
}

The output of this program is given below:

Whip Milk Coffee
Cost: 2.2

Implementation in JavaScript
// Class to be decorated
function Coffee() {
    this.cost = function() {
return 1;
    };
}
// Decorator A
function Milk(coffee) {
    this.cost = function() {
return coffee.cost() + 0.5;
    };
}
// Decorator B
function Whip(coffee) {
    this.cost = function() {
return coffee.cost() + 0.7;
    };
}
// Decorator C
function Sprinkles(coffee) {
    this.cost = function() {
return coffee.cost() + 0.2;
    };
}
// Here's one way of using it
var coffee = new Milk(new Whip(new Sprinkles(new Coffee())));
alert( coffee.cost() );
// Here's another
var coffee = new Coffee();
coffee = new Sprinkles(coffee);
coffee = new Whip(coffee);
coffee = new Milk(coffee);
alert(coffee.cost());
Implementation in Kotlin
fun printInfo(c: Coffee) {
    println("Cost: " + c.cost + "; Ingredients: " + c.ingredients)
}

fun main(args: Array<String>) {
    var c: Coffee = SimpleCoffee()
    printInfo(c)

    c = WithMilk(c)
    printInfo(c)

    c = WithSprinkles(c)
    printInfo(c)
}

// The interface Coffee defines the functionality of Coffee implemented by decorator
interface Coffee {
    val cost: Double // Returns the cost of the coffee
    val ingredients: String // Returns the ingredients of the coffee
}

// Extension of a simple coffee without any extra ingredients
class SimpleCoffee : Coffee {
    override val cost: Double
        get() = 1.0

    override val ingredients: String
        get() = "Coffee"
}

// Abstract decorator class - note that it implements Coffee interface
abstract class CoffeeDecorator(private val decoratedCoffee: Coffee) : Coffee {

    override// Implementing methods of the interface
    val cost: Double
        get() = decoratedCoffee.cost

    override val ingredients: String
        get() = decoratedCoffee.ingredients
}

// Decorator WithMilk mixes milk into coffee.
// Note it extends CoffeeDecorator.
class WithMilk(c: Coffee) : CoffeeDecorator(c) {

    override// Overriding methods defined in the abstract superclass
    val cost: Double
        get() = super.cost + 0.5

    override val ingredients: String
        get() = super.ingredients + ", Milk"
}

// Decorator WithSprinkles mixes sprinkles onto coffee.
// Note it extends CoffeeDecorator.
class WithSprinkles(c: Coffee) : CoffeeDecorator(c) {

    override val cost: Double
        get() = super.cost + 0.2

    override val ingredients: String
        get() = super.ingredients + ", Sprinkles"
}

The output of this program is given below:

Cost: 1.0; Ingredients: Coffee
Cost: 1.5; Ingredients: Coffee, Milk
Cost: 1.7; Ingredients: Coffee, Milk, Sprinkles

Implementation in Java

First Example (window/scrolling scenario)

The following Java example illustrates the use of decorators using the window/scrolling scenario.

// the Window abstract class
public abstract class Window {
    public abstract void draw(); // draws the Window
    public abstract String getDescription(); // returns a description of the Window
}
// extension of a simple Window without any scrollbars
class SimpleWindow extends Window {
    public void draw() {
        // draw window
    }
    public String getDescription() {
        return "simple window";
    }
}

The following classes contain the decorators for all Window classes, including the decorator classes themselves.

// abstract decorator class - note that it extends Window
abstract class WindowDecorator extends Window {
    protected Window decoratedWindow; // the Window being decorated
    public WindowDecorator (Window decoratedWindow) {
        this.decoratedWindow = decoratedWindow;
    }
    public void draw() {
        decoratedWindow.draw(); //delegation
    }
    public String getDescription() {
        return decoratedWindow.getDescription(); //delegation
    }
}
// the first concrete decorator which adds vertical scrollbar functionality
class VerticalScrollBarDecorator extends WindowDecorator {
    public VerticalScrollBarDecorator (Window decoratedWindow) {
        super(decoratedWindow);
    }
    @Override
    public void draw() {
        super.draw();
        drawVerticalScrollBar();
    }
    private void drawVerticalScrollBar() {
        // draw the vertical scrollbar
    }
    @Override
    public String getDescription() {
        return super.getDescription() + ", including vertical scrollbars";
    }
}
// the second concrete decorator which adds horizontal scrollbar functionality
class HorizontalScrollBarDecorator extends WindowDecorator {
    public HorizontalScrollBarDecorator (Window decoratedWindow) {
        super(decoratedWindow);
    }
    @Override
    public void draw() {
        super.draw();
        drawHorizontalScrollBar();
    }
    private void drawHorizontalScrollBar() {
        // draw the horizontal scrollbar
    }
    @Override
    public String getDescription() {
        return super.getDescription() + ", including horizontal scrollbars";
    }
}

Here's a test program that creates a Window instance which is fully decorated (i.e., with vertical and horizontal scrollbars), and prints its description:

public class DecoratedWindowTest {
    public static void main(String[] args) {
        // create a decorated Window with horizontal and vertical scrollbars
        Window decoratedWindow = new HorizontalScrollBarDecorator (
                new VerticalScrollBarDecorator(new SimpleWindow()));
        // print the Window's description
        System.out.println(decoratedWindow.getDescription());
    }
}

The output of this program is "simple window, including vertical scrollbars, including horizontal scrollbars". Notice how the getDescription method of the two decorators first retrieve the decorated Window's description and decorates it with a suffix.

Second Example (coffee making scenario)

The next Java example illustrates the use of decorators using coffee making scenario. In this example, the scenario only includes cost and ingredients.

// The abstract Coffee class defines the functionality of Coffee implemented by decorator
public abstract class Coffee {
    public abstract double getCost(); // returns the cost of the coffee
    public abstract String getIngredients(); // returns the ingredients of the coffee
}
// extension of a simple coffee without any extra ingredients
public class SimpleCoffee extends Coffee {
    public double getCost() {
        return 1;
    }
    public String getIngredients() {
        return "Coffee";
    }
}

The following classes contain the decorators for all Coffee classes, including the decorator classes themselves..

// abstract decorator class - note that it extends Coffee abstract class
public abstract class CoffeeDecorator extends Coffee {
    protected final Coffee decoratedCoffee;
    protected String ingredientSeparator = ", ";
    public CoffeeDecorator(Coffee decoratedCoffee) {
        this.decoratedCoffee = decoratedCoffee;
    }
    public double getCost() { // implementing methods of the abstract class
        return decoratedCoffee.getCost();
    }
    public String getIngredients() {
        return decoratedCoffee.getIngredients();
    }
}
// Decorator Milk that mixes milk with coffee
// note it extends CoffeeDecorator
class Milk extends CoffeeDecorator {
    public Milk(Coffee decoratedCoffee) {
        super(decoratedCoffee);
    }
    public double getCost() { // overriding methods defined in the abstract superclass
        return super.getCost() + 0.5;
    }
    public String getIngredients() {
        return super.getIngredients() + ingredientSeparator + "Milk";
    }
}
// Decorator Whip that mixes whip with coffee
// note it extends CoffeeDecorator
class Whip extends CoffeeDecorator {
    public Whip(Coffee decoratedCoffee) {
        super(decoratedCoffee);
    }
    public double getCost() {
        return super.getCost() + 0.7;
    }
    public String getIngredients() {
        return super.getIngredients() + ingredientSeparator + "Whip";
    }
}
// Decorator Sprinkles that mixes sprinkles with coffee
// note it extends CoffeeDecorator
class Sprinkles extends CoffeeDecorator {
    public Sprinkles(Coffee decoratedCoffee) {
        super(decoratedCoffee);
    }
    public double getCost() {
        return super.getCost() + 0.2;
    }
    public String getIngredients() {
        return super.getIngredients() + ingredientSeparator + "Sprinkles";
    }
}

Here's a test program that creates a Coffee instance which is fully decorated (i.e., with milk, whip, sprinkles), and calculate cost of coffee and prints its ingredients:

public class Main {
   
    public static final void main(String[] args) {
Coffee c = new SimpleCoffee();
System.out.println("Cost: " + c.getCost() + "; Ingredients: " + c.getIngredients());
c = new Milk(c);
System.out.println("Cost: " + c.getCost() + "; Ingredients: " + c.getIngredients());
c = new Sprinkles(c);
System.out.println("Cost: " + c.getCost() + "; Ingredients: " + c.getIngredients());
c = new Whip(c);
System.out.println("Cost: " + c.getCost() + "; Ingredients: " + c.getIngredients());
// Note that you can also stack more than one decorator of the same type
c = new Sprinkles(c);
System.out.println("Cost: " + c.getCost() + "; Ingredients: " + c.getIngredients());
    }
   
}

The output of this program is given below:

Cost: 1.0 Ingredient: Coffee
Cost: 1.5 Ingredient: Coffee, Milk
Cost: 1.7 Ingredient: Coffee, Milk, Sprinkles
Cost: 2.4 Ingredient: Coffee, Milk, Sprinkles, Whip

Implementation in Python

Window System

# the Window base class
class Window(object):
    def draw(self, device):
        device.append('flat window')
    def info(self):
        pass
# The decorator pattern approch
class WindowDecorator:
    def __init__(self, w):
        self.window = w
    def draw(self, device):
        self.window.draw(device)
    def info(self):
        self.window.info()
class BorderDecorator(WindowDecorator):
    def draw(self, device):
        self.window.draw(device)
        device.append('borders')
class ScrollDecorator(WindowDecorator):
    def draw(self, device):
        self.window.draw(device)
        device.append('scroll bars')
def test_deco():
    # The way of using the decorator classes
    w = ScrollDecorator(BorderDecorator(Window()))
    dev = []
    w.draw(dev)
    print dev
test_deco()

Difference between subclass method and decorator pattern

# The subclass approch
class BorderedWindow(Window):
    def draw(self, device):
        super(BorderedWindow, self).draw(device)
        device.append('borders')
class ScrolledWindow(Window):
    def draw(self, device):
        super(ScrolledWindow, self).draw(device)
        device.append('scroll bars')
# combine the functionalities using multiple inheritance.
class MyWindow(ScrolledWindow, BorderedWindow, Window):
    pass
def test_muli():
    w = MyWindow()
    dev = []
    w.draw(dev)
    print dev
def test_muli2():
    # note that python can create a class on the fly.
    MyWindow = type('MyWindow', (ScrolledWindow, BorderedWindow, Window), {})
    w = MyWindow()
    dev = []
    w.draw(dev)
    print dev
test_muli()
test_muli2()
Implementation in F#

Coffee example

type Coffee() = 
    abstract member Cost : double
    abstract member Ingredients: string list
    
    default this.Cost = 1.0
    default this.Ingredients = ["Coffee"]

type CoffeeDecorator(coffee: Coffee) = 
     inherit Coffee ()
     override this.Cost = coffee.Cost
     override this.Ingredients = coffee.Ingredients

type WithMilk(coffee: Coffee) = 
    inherit CoffeeDecorator(coffee)
    override this.Cost = base.Cost + 0.5
    override this.Ingredients = ["Milk"] |> List.append base.Ingredients

type WithSprinkles(coffee: Coffee) = 
    inherit CoffeeDecorator(coffee)
    override this.Cost = base.Cost + 0.2
    override this.Ingredients = ["Sprinkles"] |> List.append base.Ingredients

let print (coffee: Coffee) = 
    printfn "Cost: %.2f$; Ingredients: %A" coffee.Cost coffee.Ingredients       

let withAddins = Coffee() |> WithMilk |> WithSprinkles
print withAddins

Dynamic languages

The decorator pattern can also be implemented in dynamic languages either with interfaces or with traditional OOP inheritance.

External links

Facade

A Facade pattern hides the complexities of the system and provides an interface to the client from where the client can access the system. Dividing a system into subsystems helps reduce complexity. We need to minimize the communication and dependencies between subsystems. For this, we introduce a facade object that provides a single, simplified interface to the more general facilities of a subsystem.

Examples

The SCP command is a shortcut for SSH commands. A remote file copy could be done writing several commands with an SSH connection but it can be done in one command with SCP. So the SCP command is a facade for the SSH commands. Although it may not be coded in the object programming paradigm, it is a good illustration of the design pattern.

Cost

This pattern is very easy and has not additional cost.

Creation

This pattern is very easy to create.

Maintenance

This pattern is very easy to maintain.

Removal

This pattern is very easy to remove too.

Advises

  • Do not use this pattern to mask only three or four method calls.

Implementations

Implementation in Java

This is an abstract example of how a client ("you") interacts with a facade (the "computer") to a complex system (internal computer parts, like CPU and HardDrive).

/* Complex parts */

class CPU {
    public void freeze() { ... }
    public void jump(long position) { ... }
    public void execute() { ... }
}
class Memory {
    public void load(long position, byte[] data) { ... }
}
class HardDrive {
    public byte[] read(long lba, int size) { ... }
}
/* Facade */

class Computer {
    private CPU processor;
    private Memory ram;
    private HardDrive hd;

    public Computer() {
        this.processor = new CPU();
        this.ram = new Memory();
        this.hd = new HardDrive();
    }

    public void start() {
        processor.freeze();
        ram.load(BOOT_ADDRESS, hd.read(BOOT_SECTOR, SECTOR_SIZE));
        processor.jump(BOOT_ADDRESS);
        processor.execute();
    }
}
/* Client */

class You {
    public static void main(String[] args) {
        Computer facade = new Computer();
        facade.start();
    }
}
Implementation in C#
using System;

namespace Facade
{
	public class CPU
        {
		public void Freeze() { }
		public void Jump(long addr) { }
		public void Execute() { }
	}

	public class Memory
	{
		public void Load(long position, byte[] data) { }
        }

	public class HardDrive
	{
		public byte[] Read(long lba, int size) { return null; }
	}

	public class Computer
	{
		var cpu = new CPU();
		var memory = new Memory();
		var hardDrive = new HardDrive();

		public void StartComputer()
		{
			cpu.Freeze();
			memory.Load(0x22, hardDrive.Read(0x66, 0x99));
			cpu.Jump(0x44);
			cpu.Execute();
		}
	}

	public class SomeClass
	{
            public static void Main(string[] args)
            {
                var facade = new Computer();
                facade.StartComputer();
            }
        }
}
Implementation in Ruby
# Complex parts
class CPU
  def freeze; puts 'CPU: freeze'; end
  def jump(position); puts "CPU: jump to #{position}"; end
  def execute; puts 'CPU: execute'; end
end

class Memory
  def load(position, data)
    puts "Memory: load #{data} at #{position}"
  end
end

class HardDrive
  def read(lba, size)
    puts "HardDrive: read sector #{lba} (#{size} bytes)"
    return 'hdd data'
  end
end

# Facade
class Computer
  BOOT_ADDRESS = 0
  BOOT_SECTOR = 0
  SECTOR_SIZE = 512

  def initialize
    @cpu = CPU.new
    @memory = Memory.new
    @hard_drive = HardDrive.new
  end

  def start_computer
    @cpu.freeze
    @memory.load(BOOT_ADDRESS, @hard_drive.read(BOOT_SECTOR, SECTOR_SIZE))
    @cpu.jump(BOOT_ADDRESS)
    @cpu.execute
  end
end

# Client
facade = Computer.new
facade.start_computer
Implementation in Python
# Complex parts
class CPU:
    def freeze(self): pass
    def jump(self, position): pass
    def execute(self): pass
 
class Memory:
    def load(self, position, data): pass
 
class HardDrive:
    def read(self, lba, size): pass
 
# Facade
class Computer:
    def __init__(self):
        self.cpu = CPU()
        self.memory = Memory()
        self.hard_drive = HardDrive()
    
    def start_computer(self):
        self.cpu.freeze()
        self.memory.load(0, self.hard_drive.read(0, 1024))
        self.cpu.jump(10)
        self.cpu.execute()
 
# Client
if __name__ == '__main__':
    facade = Computer()
    facade.start_computer()
Implementation in PHP
/* Complex parts */
class CPU
{
    public function freeze() { /* ... */ }
    public function jump( $position ) { /* ... */ }
    public function execute() { /* ... */ }

}

class Memory
{
    public function load( $position, $data ) { /* ... */ }
}

class HardDrive
{
    public function read( $lba, $size ) { /* ... */ }
}

/* Facade */
class Computer
{
    protected $cpu = null;
    protected $memory = null;
    protected $hardDrive = null;

    public function __construct()
    {
        $this->cpu = new CPU();
        $this->memory = new Memory();
        $this->hardDrive = new HardDrive();
    }

    public function startComputer()
    {
        $this->cpu->freeze();
        $this->memory->load( BOOT_ADDRESS, $this->hardDrive->read( BOOT_SECTOR, SECTOR_SIZE ) );
        $this->cpu->jump( BOOT_ADDRESS );
        $this->cpu->execute();
    }
}

/* Client */
$facade = new Computer();
$facade->startComputer();
Implementation in JavaScript
/* Complex parts */
var CPU = function () {};
CPU.prototype = {
  freeze: function () {
    console.log('CPU: freeze');
  },
  jump: function (position) {
    console.log('CPU: jump to ' + position);
  },
  execute: function () {
    console.log('CPU: execute');
  }
};

var Memory = function () {};
Memory.prototype = {
  load: function (position, data) {
    console.log('Memory: load "' + data + '" at ' + position);
  }
};

var HardDrive = function () {};
HardDrive.prototype = {
  read: function (lba, size) {
    console.log('HardDrive: read sector ' + lba + '(' + size + ' bytes)');
    return 'hdd data';
  }
};

/* Facade */
var Computer = function () {
  var cpu, memory, hardDrive;
  
  cpu = new CPU();
  memory = new Memory();
  hardDrive = new HardDrive();

  var constant = function (name) {
    var constants = {
      BOOT_ADDRESS: 0,
      BOOT_SECTOR: 0,
      SECTOR_SIZE: 512
    };

    return constants[name];
  };

  this.startComputer = function () {
    cpu.freeze();
    memory.load(constant('BOOT_ADDRESS'), hardDrive.read(constant('BOOT_SECTOR'), constant('SECTOR_SIZE')));
    cpu.jump(constant('BOOT_ADDRESS'));
    cpu.execute();
  }

};

/* Client */
var facade = new Computer();
facade.startComputer();
Implementation in ActionScript 3.0
/* Complex Parts */

/* CPU.as */
package
{
    public class CPU
    {
        public function freeze():void
        {
            trace("CPU::freeze");
        }
        
        public function jump(addr:Number):void
        {
            trace("CPU::jump to", String(addr));
        }
        
        public function execute():void
        {
            trace("CPU::execute");
        }
    }
}

/* Memory.as */
package
{
    import flash.utils.ByteArray;

    public class Memory
    {
        public function load(position:Number, data:ByteArray):void
        {
            trace("Memory::load position:", position, "data:", data);
        }
    }
}

/* HardDrive.as */
package
{
    import flash.utils.ByteArray;

    public class HardDrive
    {
        public function read(lba:Number, size:int):ByteArray
        {
            trace("HardDrive::read returning null");
            return null;
        }
    }
}

/* The Facade */
/* Computer.as */
package
{
    public class Computer
    {
        public static const BOOT_ADDRESS:Number = 0x22;
        public static const BOOT_SECTOR:Number = 0x66;
        public static const SECTOR_SIZE:int = 0x200;
        
        private var _cpu:CPU;
        private var _memory:Memory;
        private var _hardDrive:HardDrive;
        
        public function Computer()
        {
            _cpu = new CPU();
            _memory = new Memory();
            _hardDrive = new HardDrive();
        }
        
        public function startComputer():void
        {
            _cpu.freeze();
            _memory.load(BOOT_ADDRESS, _hardDrive.read(BOOT_SECTOR, SECTOR_SIZE));
            _cpu.jump(BOOT_ADDRESS);
            _cpu.execute();
        }
    }
}

/* Client.as : This is the application's Document class */
package
{
    import flash.display.MovieClip;
    
    public class Client extends MovieClip
    {       
        private var _computer:Computer;
        
        public function Client()
        {
            _computer = new Computer();
            _computer.startComputer();
        }
    }
}
Implementation in Scala
/* Complex parts */

package intel {
  class CPU {
    def freeze() = ???
    def jump(position: Long) = ???
    def execute() = ???
  }
}

package ram.plain {
  class Memory {
    def load(position: Long, data: Array[Byte]) = ???
  }
}

package hdd {
  class HardDrive {
    def read(lba: Long, size: Int): Array[Byte]  = ???
  }
}
/* Facade */
//imports for the facade
import common.patterns.intel.CPU
import common.patterns.ram.plain.Memory
import common.patterns.hdd.HardDrive

package pk {
  class ComputerFacade(conf: String) {
    val processor: CPU = new CPU
    val ram: Memory = new Memory
    val hd: HardDrive = new HardDrive

    val BOOT_ADDRESS: Long = ???
    val BOOT_SECTOR: Long = ???
    val SECTOR_SIZE: Int = ???

    def start() = {
      processor.freeze()
      ram.load(BOOT_ADDRESS, hd.read(BOOT_SECTOR, SECTOR_SIZE))
      processor.jump(BOOT_ADDRESS)
      processor.execute()
    }
  }
}
//imports for your package
import common.patterns.pk.ComputerFacade

/* Client */

object You {
  def main(args: Array[String]) {
    new ComputerFacade("conf").start()
  }
}
Implementation in Delphi
program Facade;

{$APPTYPE CONSOLE}
{$R *.res}

uses
  System.SysUtils;

type
  (* complex parts - > Subsystem *)
  TCPU = class
    procedure Freeze;
    procedure Jump(position: Integer);
    procedure Execute;
  end;

  TMemory = class
    procedure Load(position: Integer; data: string);
  end;

  THardDrive = class
    function Read(lba, size: Integer): string;
  end;

  (* Facade *)
  TComputer = class
    fCPU: TCPU;
    fMemory: TMemory;
    fHardDrive: THardDrive;
    
  const
    BOOT_ADDRESS: Integer = 0;
    BOOT_SECTOR: Integer = 0;
    SECTOR_SIZE: Integer = 512;
  public
    procedure Start_Computer;
    constructor Create;
  end;

  { TCPU }

procedure TCPU.Execute;
begin
  WriteLn('CPU: execute');
end;

procedure TCPU.Freeze;
begin
  WriteLn('CPU: freese');
end;

procedure TCPU.Jump(position: Integer);
begin
  WriteLn('CPU: jump to ' + IntToStr(position));
end;

{ TMemory }

procedure TMemory.Load(position: Integer; data: string);
begin
  WriteLn('Memory: load "' + data + '" at ' + IntToStr(position));
end;

{ THardDrive }

function THardDrive.Read(lba, size: Integer): string;
begin
  WriteLn('HardDrive: read sector ' + IntToStr(lba) + ' (' + IntToStr(size) +
    ' bytes)');
  Result := 'hdd data';
end;

{ TComputer }

constructor TComputer.Create;
begin
  fCPU := TCPU.Create;
  fMemory := TMemory.Create;
  fHardDrive := THardDrive.Create;
end;

procedure TComputer.Start_Computer;
begin
  fCPU.Freeze;
  fMemory.Load(BOOT_ADDRESS, fHardDrive.Read(BOOT_SECTOR, SECTOR_SIZE));
  fCPU.Jump(BOOT_ADDRESS);
  fCPU.Execute;
end;

var
  facad: TComputer;

begin
  try
    { TODO -oUser -cConsole Main : Insert code here }

    facad := TComputer.Create;
    facad.Start_Computer;
    
    WriteLn(#13#10 + 'Press any key to continue...');
    ReadLn;

    facad.Free;
  except
    on E: Exception do
      WriteLn(E.ClassName, ': ', E.Message);
  end;
end.

Factory method

The factory pattern is a design pattern used to promote encapsulation of data representation.

Problem
We want to decide at run time what object is to be created based on some configuration or application parameter. When we write the code we do not know what class should be instantiated.
Solution
Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses. Its primary purpose is to provide a way for users to retrieve an instance with a known compile-time type, but whose runtime type may actually be different. In other words, a factory method that is supposed to return an instance of the class Foo may return an instance of the class Foo, or it may return an instance of the class Bar, so long as Bar inherits from Foo. The reason for this is that it strengthens the boundary between implementor and client, hiding the true representation of the data (see Abstraction Barrier) from the user, thereby allowing the implementor to change this representation at anytime without affecting the client, as long as the client facing interface doesn't change.

Basic Implementation of the Factory Pattern

The general template for implementing the factory pattern is to provide a primary user facing class with static methods which the user can use to get instances with that type. Constructors are then made private/protected from the user, forcing them to use the static factory methods to get objects. The following Java code shows a very simple implementation of the factory pattern for type Foo.

public class Foo {
  // Static factory method
  public static Foo getInstance() {
    // Inside this class, we have access to private methods
    return new Foo();
  }
  // Guarded constructor, only accessible from within this class, since it's marked private
  private Foo() {
    // Typical initialization code goes here
  }
} // End class Foo

With this code, it would be impossible for a client of the code to use the new operator to get an instance of the class, as is traditionally done:

// Client code
Foo f = new Foo(); // Won't Work!

because the constructor is marked private. Instead, the client would have to use the factory method:

// Client code
Foo f = Foo.getInstance(); // Works!

It should be noted that even within a programming language community, there is no general consensus as to the naming convention of a factory method. Some suggest naming the method with the name of the class, similar to a normal constructor, but starting with a lowercase. Others say that this is confusing, and suggest using an accessor type syntax, like the getInstance style used above, though others complain that this may incorrectly imply a singleton implementation. Likewise, some offer newInstance, but this is criticized as being misleading in certain situations where a strictly new instance may not actually be returned (once again, refer to the singleton pattern). As such, we will not attempt to follow any particularly rigid standard here, we will simply try to use a name that makes the most sense for our current purposes.

Factory Pattern Implementation of the Alphabet

That's great, you know how to implement a real simple factory pattern, but what good did it do you? Users are asking for something that fits into type Foo, and they're getting an instance of the class Foo, how is that different from just calling the constructor? Well it's not, except that you're putting another function call on the stack (which is a bad thing). But that's only for the above case. We'll now discuss a more useful use of the factory pattern. Consider a simple type called Letter, representing a letter in the alphabet, which has the following client facing interface (i.e., public instance methods):

char toCharacter();
boolean isVowel();
boolean isConsonant();

We could implement this easily enough without using the factory method, which might start out something like this:

public class Letter {
  private char fTheLetter;
  public Letter(char aTheLetter) {
    fTheLetter = aTheLetter;
  }
  public char toCharacter() {
    return fTheLetter;
  }
  public boolean isVowel() {
    //TODO: we haven't implemented this yet
    return true;
  }
  public boolean isConsonant() {
    // TODO: we haven't implemented this yet
    return false;
  }
} // End class Letter

Fairly simple, but notice we haven't implemented the last two methods yet. We can still do it pretty easily. The first might look like this:

  public boolean isVowel() {
    return
      fTheLetter == 'a' ||
      fTheLetter == 'e' ||
      fTheLetter == 'i' ||
      fTheLetter == 'o' ||
      fTheLetter == 'u' ||
      fTheLetter == 'A' ||
      fTheLetter == 'E' ||
      fTheLetter == 'I' ||
      fTheLetter == 'O' ||
      fTheLetter == 'U';
  }

Now that's not too bad, but we still need to do isConsonant. Fortunately, we at least know in this case that if it's a vowel, it's not a consonant, and vice versa, so our last method could simply be:

  public boolean isConsonant() {
    return !this.isVowel();
  }

So what's the problem here? Basically, every time you call either of these methods, your program has to do all that checking. Granted, this isn't a real heavy burden for the Java Runtime Environment, but you can imagine a much more complex, much more time consuming operation. Wouldn't it be great if we could avoid doing this every time we call the method? Let's say, for instance, we could do it once when we create the object, and then not have to do it again. Well sure, we can do that. Here's an implementation that'll do that for us, and we still don't have to use the factory method:

public class Letter {
  private char fTheLetter;
  private boolean fIsVowel;
  public Letter(char aTheLetter) {
    fTheLetter = aTheLetter;
    fIsVowel = fTheLetter == 'a' ||
      fTheLetter == 'e' ||
      fTheLetter == 'i' ||
      fTheLetter == 'o' ||
      fTheLetter == 'u' ||
      fTheLetter == 'A' ||
      fTheLetter == 'E' ||
      fTheLetter == 'I' ||
      fTheLetter == 'O' ||
      fTheLetter == 'U';
  }
  public char toCharacter() {
    return fTheLetter;
  }
  public boolean isVowel() {
    return fIsVowel;
  }
  public boolean isConsonant() {
    return !fIsVowel;
  }
} // End class Letter

Notice how we moved the lengthy operation into the constructor, and stored the result. OK, so now we're all fine and dandy, no? Sure, but let's say you came up with a new idea, a different implementation: you want to split this type into two classes, one class to handle the vowels, and one to handle the consonants. Great, they can both be subclasses of the Letter class, and the user will never know the difference, right? Wrong. How is the client supposed to get at these new classes? They've got code that works perfectly well for them by calling new Letter('a') and new Letter('Z'). Now you're going to make them go through all their code and change these to new Vowel('a') and new Consonant('Z')? They probably won't be too happy with that. If only you could get new instances of both classes from one method! Well you can, just use a static method in the Letter class, it'll do the same one-time checking as the constructor did, and will return an appropriate instance of the right class. And what do you know, it's a factory method! But that still doesn't do your client much good, they still need to go through and change all the new Letter()s into Letter.getLetter(). Well, sad to say, it's too late to help them at all, unless you just give up your new implementation. But that illustrates the reason for using the factory method right off the bat. One of the key components of good object oriented programming is that you never know exactly where your code will go in the future. By making good use of the abstraction barrier and using encapsulation-friendly programming patterns, such as the factory pattern, you can better prepare yourself—and your client—for future changes to the specific implementation. In particular, it allows you to use a "big hammer" kind of approach to get something done in a perhaps-less-than-ideal but rapid manner in order to meet deadlines or move ahead with testing,. You can then go back later and refine the implementation—the data representation and algorithms—to be faster, smaller, or what-have-you, and as long as you maintained the abstraction barrier between implementor and client and properly encapsulated your implementation, then you can change it without requiring the client to change any of their code. Well now that I'm sure you're a raving advocate for the factory method, let's take a look at how we would implement it for our Letter type:

public abstract class Letter {
 
// Factory Method
 public static Letter getLetter(char aTheLetter) {
 // Like before, we do a one time check to see what kind of
 // letter we are dealing with. Only this time, instead of setting
 // a property to track it, we actually have a different class for each
 // of the two letter types.
 if (
 aTheLetter == 'a' ||
 aTheLetter == 'e' ||
 aTheLetter == 'i' ||
 aTheLetter == 'o' ||
 aTheLetter == 'u' ||
 aTheLetter == 'A' ||
 aTheLetter == 'E' ||
 aTheLetter == 'I' ||
 aTheLetter == 'O' ||
 aTheLetter == 'U'
 ) {
   return new Vowel(aTheLetter);
 } else {
   return new Consonant(aTheLetter);
 }
 }
 
 
// User facing interface
// We make these methods abstract, thereby requiring all subclasses
// (actually, just all concrete subclasses, that is, non-abstract)
// to implement the methods.
 public abstract boolean isVowel();
 
 public abstract boolean isConsonant();
 
 public abstract char getChar();
 
 
 // Now we define the two concrete classes for this type,
 // the ones that actually implement the type.
 private static class Vowel extends Letter {
 private char iTheLetter;
 
 // Constructor
 Vowel(char aTheLetter) {
 this.iTheLetter = aTheLetter;
 }
 
 // Nice easy implementation of this method!
 public boolean isVowel() {
 return true;
 }
 
 // This one, too!
 public boolean isConsonant() {
 return false;
 }
 public char getLetter(){
   return iTheLetter;
 }
 } // End local class Vowel
 private static class Consonant extends Letter {
 private char iTheLetter;
 
 // Constructor
 Consonant(char aTheLetter) {
   this.iTheLetter = aTheLetter;
 }
 
 public boolean isVowel() {
   return false;
 }
 
 public boolean isConsonant(){
   return true;
 }
 public char getLetter(){
   return iTheLetter;
 }
 } // End local class Consonant
 
} // End toplevel class Letter

Several things to note here.

  • First, you'll notice the top level class Letter is abstract. This is fine because you'll notice that it doesn't actually do anything except define the interface and provide a top level container for the two other classes. However, it's also important (not just OK) to make this abstract because we don't want people trying to instantiate the Letter class directly. Of course we could solve this problem by making a private constructor, but making the class abstract instead is cleaner, and makes it more obvious that the Letter class is not meant to be instantiated. It also, as mentioned, allows us to define the user facing interface that the work horse classes need to implement.
  • The two nested classes we created are called local classes, which is basically the same as an inner class except that local classes are static, and inner classes are not. They have to be static so that our static factory method can create them. If they were non static (i.e., dynamic) then they could only be accessed through an instance of the Letter class, which we can never have because Letter is abstract. Also note that (in Java, anyway) the fields for inner and local classes typically use the "i" (for inner) prefix, as opposed to the "f" (for field) prefix used by top level classes. This is simply a naming convention used by many Java programmers and doesn't actually effect the program.
  • The two nested classes that implement the Letter data type do not actually have to be local/inner. They could just have easily been top level classes that extend the abstract Letter class. However, this is contrary to the point of the factory pattern, which is encapsulation. Top level classes can't be private in Java, because that doesn't make any sense (what are they private to?) and the whole point is that no client has to (or should, really) know how the type is implemented. Making these classes top level allows clients to potentially stumble across them, and worse yet, instantiate them, by-passing the factory pattern all together.
  • Lastly, this is not very good code. There's a lot of ways we can make it better to really illustrate the power of the factory pattern. I'll discuss these refactorings briefly, and then show another, more polished, version of the above code which includes a lot of them.

Refactoring the Factory Pattern

Notice that both of the local classes do the same thing in a few places. This is redundant code which is not only more work to write, but it's also highly discouraged in object oriented programming (partially because it takes more work to write, but mostly because it's harder to maintain and prone to errors, e.g., you find a bug in the code and change it in one spot, but forget to in another.) Below is a list of redundancies in the above code:

  • The field iTheLetter
  • The method getLetter()
  • The constructor of each inner class does the same thing.

In addition, as we discovered above, the isVowel() and isConsonant() just happen to always return the opposite of each other for a given instance. However, since this is something of a peculiarity for this particular example, we won't worry about it. The lesson you would learn from us doing that will already be covered in the refactoring of the getLetter() method. OK, so we have redundant code in two classes. If you're familiar with abstracting processes, then this is probably a familiar scenario to you. Often, having redundant code in two different classes makes them prime candidates for abstraction, meaning that a new abstract class is created to implement the redundant code, and the two classes simply extend this new abstract class instead of implementing the redundant code. Well what do you know? We already have an abstract super class that our redundant classes have in common. All we have to do is make the super class implement the redundant code, and the other classes will automatically inherit this implementation, as long as we don't override it. So that works fine for the getLetter() method, we can move both the method and the iTheLetter field up to the abstract parent class. But what about the constructors? Well our constructor takes an argument, so we won't automatically inherit it, that's just the way java works. But we can use the super keyword to automatically delegate to the super classes constructor. In other words, we'll implement the constructor in the super class, since that's where the field is anyway, and the other two classes will delegate to this method in their own constructors. For our example, this doesn't save much work, we're replacing a one line assignment with a one line call to super(), but in theory, there could be hundred of lines of code in the constructors, and moving it up could be a great help. At this point, you might be a little worried about putting a constructor in the Letter class. Didn't I already say not to do that? I thought we didn't want people trying to instantiate Letter directly? Don't worry, the class is still abstract. Even if there's a concrete constructor, Java won't let you instantiate an abstract class, because it's abstract, it could have method that are accessible but undefined, and it wouldn't know what to do if such a method was invoked. So putting the constructor in is fine. After making the above refactorings, our code now looks like this:

public abstract class Letter {
 
// Factory Method
 public static Letter getLetter(char aTheLetter){
 if (
 aTheLetter == 'a' ||
 aTheLetter == 'e' ||
 aTheLetter == 'i' ||
 aTheLetter == 'o' ||
 aTheLetter == 'u' ||
 aTheLetter == 'A' ||
 aTheLetter == 'E' ||
 aTheLetter == 'I' ||
 aTheLetter == 'O' ||
 aTheLetter == 'U'
 ) {
   return new Vowel(aTheLetter);
 } else {
   return new Consonant(aTheLetter);
 }
 }
 
 
 // Our new abstracted field. We'll make it protected so that subclasses can see it,
 // and we rename it from "i" to "f", following our naming convention.
 protected char fTheLetter;
 
 
 // Our new constructor. It can't actually be used to instantiate an instance
 // of Letter, but our sub classes can invoke it with super
 protected Letter(char aTheLetter) {
 this.fTheLetter = aTheLetter;
 }
 
 // The new method we're abstracting up to remove redundant code in the sub classes
 public char getChar() {
 return this.fTheLetter;
 }
 // Same old abstract methods that define part of our client facing interface
 public abstract boolean isVowel();
 
 public abstract boolean isConsonant();
 
 
 
 // The local subclasses with the redundant code moved up.
 
 private static class Vowel extends Letter {
 
 // Constructor delegates to the super constructor
 Vowel(char aTheLetter) {
   super(aTheLetter);
 }
 
 // Still need to implement the abstract methods
 public boolean isVowel()  {
   return true;
 }
 
 public boolean isConsonant(){
   return false;
 }
 } // End local class Vowel
 
 
 private static class Consonant extends Letter {
 
 Consonant(char aTheLetter){
   super(aTheLetter);
 }
 
 public boolean isVowel(){
   return false;
 }
 
 public boolean isConsonant(){
   return true;
 }
 } // End local class Consonant
 
} // End toplevel class Letter

Note that we made our abstracted field protected. This isn't strictly necessary in this case, we could have left it private, because the subclasses don't actually need to access it at all. In general, I prefer to make things protected instead of private, since, as I mentioned, you can never really be sure where a project will go in the future, and you may not want to restrict future implementors (including yourself) unnecessarily. However, many people prefer to default to private and only use protected when they know it's necessary. A major reason for this is the rather peculiar and somewhat unexpected meaning of protected in Java, which allows not only subclasses, but anything in the same package to access it. This is a bit of a digression, but I think it's a fairly important debate that a good Java programmer should be aware of.

The Factory Pattern and Parametric Polymorphism

The version of the Java Virtual Machine 5.0 has introduced something called Parametric Polymorphism, which goes by many other names in other languages, including "generic typing" in C++. In order to really understand the rest of this section, you should read that section first. But basically, this means that you can introduce additional parameters into a class—parameters which are set at instantiation—that define the types of certain elements in the class, for instance fields or method return values. This is a very powerful tool which allows programmers to avoid a lot of those nasty instanceofs and narrowing castes. However, the implementation of this device in the JVM does not promote the use of the Factory pattern, and in the two do not play well together. This is because Java does not allow methods to be parameterized the way types are, so you cannot dynamically parameterize an instance through a method, only through use of the new operator. As an example, imagine a type Foo which is parameterized with a single type which we'll call T. In java we would write this class like this:

class Foo<T> {
} // End class Foo

Now we can have instances of Foo parameterized by all sorts of types, for instance:

Foo<String> fooOverString = new Foo<String>();
Foo<Integer> fooOverInteger = new Foo<Integer>();

But let's say we want to use the factory pattern for Foo. How do we do that? You could create a different factory method for each type you want to parameterize over, for instance:

class Foo<T> {
  static Foo<String> getFooOverString() {
    return new Foo<String>();
  }
  static Foo<Integer> getFooOverInteger() {
    return new Foo<Integer>();
  }
} // End class Foo

But what about something like the ArrayList class (in the java.util package)? In the java standard libraries released with 5.0, ArrayList is parameterized to define the type of the object stored in it. We certainly don't want to restrict what kinds of types it can be parameterized with by having to write a factory method for each type. This is often the case with parameterized types: you don't know what types users will want to p