Jump to content

Factory method pattern

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by 173.61.86.226 (talk) at 11:01, 24 June 2023. The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
Factory method in UML
Factory Method in LePUS3

The factory method pattern is an object-oriented design pattern to implement the concept of factories.

Like other creational patterns, it deals with the problem of creating objects (products) without specifying the exact class of object that will be created. The factory method design pattern handles this problem by defining a separate method for creating the objects, which subclasses can then override to specify the derived type of product that will be created.

Outside the scope of design patterns, the term factory method can also refer to a method of a factory whose main purpose is creation of objects.

Definition

The essence of the Factory method Pattern is to "Define an interface for creating an object, but let the subclasses decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses."[1]

Common usage

Factory methods are common in toolkits and frameworks where library code needs to create objects of types which may be subclassed by applications using the framework.

Parallel class hierarchies often require objects from one hierarchy to be able to create appropriate objects from another.

Factory methods are used in test-driven development to allow classes to be put under test[2]. If such a class Foo creates another object Dangerous that can't be put under automated unit tests (perhaps it communicates with a production database that isn't always available), then the creation of Dangerous objects is placed in the virtual factory method createDangerous in class Foo. For testing, TestFoo (a subclass of Foo) is then created, with the virtual factory method createDangerous overridden to create and return FakeDangerous, a fake object. Unit tests then use TestFoo to test the functionality of Foo without incurring the side effect of using a real Dangerous object.

Other benefits and variants

Although the motivation behind the factory method pattern is to allow subclasses to choose which type of object to create, there are other benefits to using factory methods, many of which do not depend on subclassing. Therefore, it is common to define "factory methods" that are not polymorphic to create objects in order to gain these other benefits. Such methods are often static.

Descriptive names

A factory method has a distinct name. In many object-oriented languages, constructors must have the same name as the class they are in, which can lead to ambiguity if there is more than one way to create an object (see overloading). Factory methods have no such constraint and can have descriptive names. As an example, when complex numbers are created from two real numbers the real numbers can be interpreted as Cartesian or polar coordinates, but using factory methods, the meaning is clear (the following examples are in Java):

class Complex 
{
     public static Complex fromCartesian(double real, double imag) {
         return new Complex(real, imag);
     }
 
     public static Complex fromPolar(double modulus, double angle) {
         return new Complex(modulus * cos(angle), modulus * sin(angle));
     }
  
     private Complex(double a, double b) {
         //...
     }
}
  
 Complex c = Complex.fromPolar(1, pi);

When factory methods are used for disambiguation like this, the constructor is often made private to force clients to use the factory methods.

Encapsulation

Factory methods encapsulate the creation of objects. This can be useful if the creation process is very complex, for example if it depends on settings in configuration files or on user input.

Consider as an example a program to read image files and make thumbnails out of them. The program supports different image formats, represented by a reader class for each format:

public interface ImageReader {
    public DecodedImage getDecodedImage();
}
 
public class GifReader implements ImageReader { 
    public DecodedImage getDecodedImage() {
        return decodedImage;
    }
}
 
public class JpegReader implements ImageReader {
    // ....
}

Each time the program reads an image it needs to create a reader of the appropriate type based on some information in the file. This logic can be encapsulated in a factory method:

public class ImageReaderFactory {
    public static ImageReader getImageReader(InputStream is) {
        int imageType = determineImageType(is);

        switch(imageType) {
            case ImageReaderFactory.GIF:
                return new GifReader(is);
            case ImageReaderFactory.JPEG:
                return new JpegReader(is);
            // etc.
        }
    }
}

The code fragment in the previous example uses a switch statement to associate an imageType with a specific factory object. Alternatively, this association could also be implemented as a mapping. This would allow the switch statement to be replaced with an associative array lookup.

Limitations

There are three limitations associated with the use of the factory method. The first relates to refactoring existing code; the other two relate to extending a class.

  • The first limitation is that refactoring an existing class to use factories breaks existing clients. For example, if class Complex was a standard class, it might have numerous clients with code like:
Complex c = new Complex(-1, 0);
Once we realize that two different factories are needed, we change the class (to the code shown earlier). But since the constructor is now private, the existing client code no longer compiles.
  • The second limitation is that, since the pattern relies on using a private constructor, the class cannot be extended. Any subclass must invoke the inherited constructor, but this cannot be done if that constructor is private.
  • The third limitation is that, if we do extend the class (e.g., by making the constructor protected -- this is risky but possible), the subclass must provide its own re-implementation of all factory methods with exactly the same signatures. For example, if class StrangeComplex extends Complex, then unless StrangeComplex provides its own version of all factory methods, the call StrangeComplex.fromPolar(1, pi) will yield an instance of Complex (the superclass) rather than the expected instance of the subclass.

All three problems could be alleviated by altering the underlying programming language to make factories first-class class members (see also Virtual class). [3]

Example

ABAP

REPORT zz_pizza_factory_test NO STANDARD PAGE HEADING .

TYPES ty_pizza_type TYPE i .

*----------------------------------------------------------------------*
*       CLASS lcl_pizza DEFINITION
*----------------------------------------------------------------------*
CLASS lcl_pizza DEFINITION ABSTRACT .

  PUBLIC SECTION .

    DATA p_pizza_name TYPE string .

    METHODS get_price ABSTRACT
                      RETURNING value(y_price) TYPE i .

ENDCLASS .                    "lcl_pizza DEFINITION

*----------------------------------------------------------------------*
*       CLASS lcl_ham_and_mushroom_pizza DEFINITION
*----------------------------------------------------------------------*
CLASS lcl_ham_and_mushroom_pizza DEFINITION INHERITING FROM lcl_pizza .

  PUBLIC SECTION .

    METHODS constructor .
    METHODS get_price REDEFINITION .

ENDCLASS .                    "lcl_ham_and_mushroom_pizza DEFINITION

*----------------------------------------------------------------------*
*       CLASS lcl_deluxe_pizza DEFINITION
*----------------------------------------------------------------------*
CLASS lcl_deluxe_pizza DEFINITION INHERITING FROM lcl_pizza .

  PUBLIC SECTION .

    METHODS constructor .
    METHODS get_price REDEFINITION .

ENDCLASS .                    "lcl_ham_and_mushroom_pizza DEFINITION

*----------------------------------------------------------------------*
*       CLASS lcl_hawaiian_pizza DEFINITION
*----------------------------------------------------------------------*
CLASS lcl_hawaiian_pizza DEFINITION INHERITING FROM lcl_pizza .

  PUBLIC SECTION .

    METHODS constructor .
    METHODS get_price REDEFINITION .

ENDCLASS .                    "lcl_ham_and_mushroom_pizza DEFINITION

*----------------------------------------------------------------------*
*       CLASS lcl_pizza_factory DEFINITION
*----------------------------------------------------------------------*
CLASS lcl_pizza_factory DEFINITION .
  PUBLIC SECTION .

    CONSTANTS: BEGIN OF co_pizza_type ,
                 ham_mushroom  TYPE ty_pizza_type VALUE 1 ,
                 deluxe        TYPE ty_pizza_type VALUE 2 ,
                 hawaiian      TYPE ty_pizza_type VALUE 3 ,
               END OF co_pizza_type .


    CLASS-METHODS create_pizza IMPORTING  x_pizza_type TYPE ty_pizza_type
                               RETURNING value(yo_pizza) TYPE REF TO lcl_pizza
                               EXCEPTIONS ex_invalid_pizza_type .


ENDCLASS .                    "lcl_pizza_factory DEFINITION

*----------------------------------------------------------------------*
*       CLASS lcl_ham_and_mushroom_pizza
*----------------------------------------------------------------------*
CLASS lcl_ham_and_mushroom_pizza IMPLEMENTATION .

  METHOD constructor .
    super->constructor( ) .
    p_pizza_name = 'Ham & Mushroom Pizza'(001) .
  ENDMETHOD .                    "constructor

  METHOD get_price .
    y_price = 850 .
  ENDMETHOD .                    "get_price

ENDCLASS .                    "lcl_ham_and_mushroom_pizza IMPLEMENTATION

*----------------------------------------------------------------------*
*       CLASS lcl_deluxe_pizza IMPLEMENTATION
*----------------------------------------------------------------------*
CLASS lcl_deluxe_pizza IMPLEMENTATION .

  METHOD constructor .
    super->constructor( ) .
    p_pizza_name = 'Deluxe Pizza'(002) .
  ENDMETHOD .                    "constructor

  METHOD get_price .
    y_price = 1050 .
  ENDMETHOD .                    "get_price

ENDCLASS .                    "lcl_deluxe_pizza IMPLEMENTATION

*----------------------------------------------------------------------*
*       CLASS lcl_hawaiian_pizza IMPLEMENTATION
*----------------------------------------------------------------------*
CLASS lcl_hawaiian_pizza IMPLEMENTATION .

  METHOD constructor .
    super->constructor( ) .
    p_pizza_name = 'Hawaiian Pizza'(003) .
  ENDMETHOD .                    "constructor

  METHOD get_price .
    y_price = 1150 .
  ENDMETHOD .                    "get_price

ENDCLASS .                    "lcl_hawaiian_pizza IMPLEMENTATION

*----------------------------------------------------------------------*
*       CLASS lcl_pizza_factory IMPLEMENTATION
*----------------------------------------------------------------------*
CLASS lcl_pizza_factory IMPLEMENTATION .

  METHOD create_pizza .

    CASE x_pizza_type .
      WHEN co_pizza_type-ham_mushroom .
        CREATE OBJECT yo_pizza TYPE lcl_ham_and_mushroom_pizza .
      WHEN co_pizza_type-deluxe .
        CREATE OBJECT yo_pizza TYPE lcl_deluxe_pizza .
      WHEN co_pizza_type-hawaiian .
        CREATE OBJECT yo_pizza TYPE lcl_hawaiian_pizza .
    ENDCASE .

  ENDMETHOD .                    "create_pizza

ENDCLASS .                    "lcl_pizza_factory IMPLEMENTATION


START-OF-SELECTION .

  DATA go_pizza TYPE REF TO lcl_pizza .
  DATA lv_price TYPE i .

  DO 3 TIMES .

    go_pizza = lcl_pizza_factory=>create_pizza( sy-index ) .
    lv_price = go_pizza->get_price( ) .
    WRITE:/ 'Price of', go_pizza->p_pizza_name, 'is £', lv_price LEFT-JUSTIFIED .

  ENDDO .

*Output:
*Price of Ham & Mushroom Pizza is £ 850
*Price of Deluxe Pizza is £ 1.050      
*Price of Hawaiian Pizza is £ 1.150


ActionScript 3.0

public class Pizza {
	protected var _price:Number;
	public function get price():Number {
		return _price;
	}
}

public class HamAndMushroomPizza extends Pizza {
	public function HamAndMushroomPizza() {
		_price = 8.5;
	}
}

public class DeluxePizza extends Pizza {
	public function DeluxePizza() {
		_price = 10.5;
	}
}

public class HawaiianPizza extends Pizza {
	public function HawaiianPizza() {
		_price = 11.5;
	}
}

public class PizzaFactory {
	static public function createPizza(type:String):Pizza {
		switch (type) {
			case "HamAndMushroomPizza":
				return new HamAndMushroomPizza();
				break;
				
			case "DeluxePizza":
				return new DeluxePizza();
				break;
				
			case "HawaiianPizza":
				return new HawaiianPizza();
				break;
				
			default:
				throw new ArgumentError("The pizza type " + type + " is not recognized.");
		}
	}
}

public class Main extends Sprite {
	public function Main() {
		for each (var pizza:String in ["HamAndMushroomPizza", "DeluxePizza", "HawaiianPizza"]) {
			trace("Price of " + pizza + " is " + PizzaFactory.createPizza(pizza).price);
		}
	}
}

Output:
Price of HamAndMushroomPizza is 8.5
Price of DeluxePizza is 10.5
Price of HawaiianPizza is 11.5

C++

C++ Example:

#include <string>
#include <iostream>

class Document {
private:
	char name[25];
public:
	Document(char *nm)
	{
		strcpy(name,nm);
	}
	char *getName()
	{
		return name;
	}
	virtual void Open()=0;
	virtual void Close()=0;
};

class View {
private:
	char name[25];
public:
	View(char *nm)
	{
		strcpy(name,nm);
	}
	virtual void Init()=0;
	virtual void Draw()=0;
};

class Application {
public:
	Document* newDocument(char *nm)
	{
		return createDocument(nm);
	}
	View* newView(char *nm)
	{
		return createView(nm);
	}
	virtual Document* createDocument(char *)=0;
	virtual View* createView(char *)=0;
};

// application specific class, which use the framework

class HelloDocument : public Document {
public:
	HelloDocument(char *nm):Document(nm)
	{

	}
	void Open()
	{
		cout << "\n\tOpening the hello document";
	}
	void Close()
	{
		cout << "\n\tClosing the hello document";
	}
};

class HelloView : public View {
public:
	HelloView(char *nm):View(nm)
	{

	}
	void Init()
	{
		cout << "\n\tInitializing the hello view";
	}
	void Draw()
	{
		cout << "\n\tDrawing in hello view";
	}
};

class HelloApplication : public Application {
public:
	Document* createDocument(char *nm)
	{
		return new HelloDocument(nm);
	}
	View* createView(char *nm)
	{
		return new HelloView(nm);
	}
};


int main()
{
	HelloApplication happ;
	
	HelloDocument *pDoc = (HelloDocument *)happ.newDocument("hello doc");
	HelloView *pView = (HelloView *)happ.newView("abc");

}

C#

public interface IPizza
{
    decimal Price { get; }
}

public class HamAndMushroomPizza : IPizza
{
    decimal IPizza.Price
    {
        get
        {
            return 8.5m;
        }
    }
}

public class DeluxePizza : IPizza
{
    decimal IPizza.Price
    {
        get
        {
            return 10.5m;
        }
    }
}

public class HawaiianPizza : IPizza
{
    decimal IPizza.Price
    {
        get
        {
            return 11.5m;
        }
    }
}

public class PizzaFactory
{
    public enum PizzaType
    {
        HamMushroom,
        Deluxe,
        Hawaiian
    }

    public static IPizza CreatePizza(PizzaType pizzaType)
    {
        IPizza ret = null;

        switch (pizzaType)
        {
            case PizzaType.HamMushroom:
                ret = new HamAndMushroomPizza();

                break;
            case PizzaType.Deluxe:
                ret = new DeluxePizza();

                break;
            case PizzaType.Hawaiian:
                ret = new HawaiianPizza();

                break;
            default:
                throw new ArgumentException("The pizza type " + pizzaType + " is not recognized.");
        }

        return ret;
    }
}

public class PizzaLover
{
    public static void Main(string[] args)
    {
        Dictionary<PizzaFactory.PizzaType, IPizza> pizzas = new Dictionary<PizzaFactory.PizzaType, IPizza>();
        
        foreach (PizzaFactory.PizzaType pizzaType in Enum.GetValues(typeof(PizzaFactory.PizzaType)))
        {
            pizzas.Add(pizzaType, PizzaFactory.CreatePizza(pizzaType));
        }
        
        foreach (PizzaFactory.PizzaType pizzaType in pizzas.Keys)
        {
            System.Console.WriteLine("Price of {0} is {1}", pizzaType, pizzas[pizzaType].Price);
        }
    }
}

Output:
Price of HamMushroom is 8.5
Price of Deluxe is 10.5
Price of Hawaiian is 11.5

Factory methods are not really needed, because classes and class names are first class values.

(defclass pizza ()
  ((price :accessor price)))

(defclass ham-and-mushroom-pizza (pizza)
  ((price :initform 850)))

(defclass deluxe-pizza (pizza)
  ((price :initform 1050)))

(defclass hawaiian-pizza (pizza)
  ((price :initform 1150)))

(defparameter *pizza-types*
  (list 'ham-and-mushroom-pizza
        'deluxe-pizza
        'hawaiian-pizza))

(loop for pizza-type in *pizza-types*
      do (format t "~%Price of ~a is ~a"
                 pizza-type
                 (price (make-instance pizza-type))))

Output:
Price of HAM-AND-MUSHROOM-PIZZA is 850
Price of DELUXE-PIZZA is 1050
Price of HAWAIIAN-PIZZA is 1150

Java

abstract class Pizza {
    public abstract int getPrice(); // count the cents
}

class HamAndMushroomPizza extends Pizza {
    public int getPrice() {
        return 850;
    }
}

class DeluxePizza extends Pizza {
    public int getPrice() {
        return 1050;
    }
}

class HawaiianPizza extends Pizza {
    public int getPrice() {
        return 1150;
    }
}

class PizzaFactory {
    public enum PizzaType {
        HamMushroom,
        Deluxe,
        Hawaiian
    }

    public static Pizza createPizza(PizzaType pizzaType) {
        switch (pizzaType) {
            case HamMushroom:
                return new HamAndMushroomPizza();
            case Deluxe:
                return new DeluxePizza();
            case Hawaiian:
                return new HawaiianPizza();
        }
        throw new IllegalArgumentException("The pizza type " + pizzaType + " is not recognized.");
    }
}

class PizzaLover {
    /*
     * Create all available pizzas and print their prices
     */
    public static void main (String args[]) {
        for (PizzaFactory.PizzaType pizzaType : PizzaFactory.PizzaType.values()) {
            System.out.println("Price of " + pizzaType + " is " + PizzaFactory.createPizza(pizzaType).getPrice());
        }
    }
}

Output:
Price of HamMushroom is 850
Price of Deluxe is 1050
Price of Hawaiian is 1150

Javascript

This example uses Firebug console to output information.

/**
 * Extends parent class with child. In Javascript, the keyword "extends" is not
 * currently implemented, so it must be emulated.
 * Also it is not recommended to use keywords for future use, so we name this
 * function "extends" with capital E. Javascript is case-sensitive.
 *
 * @param  function  parent constructor function
 * @param  function  (optional) used to override default child constructor function
 */
function Extends(parent, childConstructor) {

  var F = function () {};

  F.prototype = parent.prototype;

  var Child = childConstructor || function () {};
  Child.prototype = new F();
  Child.prototype.constructor = Child;
  Child.parent = parent.prototype;

  // return instance of new object
  return Child;
}


/**
 * Abstract Pizza object constructor
 */
function Pizza() {
  throw new Error('Cannot instantiate abstract object!');
}
Pizza.prototype.price = 0;
Pizza.prototype.getPrice = function () {
  return this.price;
}

var HamAndMushroomPizza = Extends(Pizza);
HamAndMushroomPizza.prototype.price = 8.5;

var DeluxePizza = Extends(Pizza);
DeluxePizza.prototype.price = 10.5;

var HawaiianPizza = Extends(Pizza);
HawaiianPizza.prototype.price = 11.5;


var PizzaFactory = {
  createPizza: function (type) {
    var baseObject = 'Pizza';
    var targetObject = type.charAt(0).toUpperCase() + type.substr(1);

    if (typeof window[targetObject + baseObject] === 'function') {
      return new window[targetObject + baseObject];
    }
    else {
      throw new Error('The pizza type ' + type + ' is not recognized.');
    }
  }
};

//var price = PizzaFactory.createPizza('deluxe').getPrice();
var pizzas = ['HamAndMushroom', 'Deluxe', 'Hawaiian'];
for (var i in pizzas) {
  console.log('Price of ' + pizzas[i] + ' is ' + PizzaFactory.createPizza(pizzas[i]).getPrice());
}

Output

Price of HamAndMushroom is 8.50
Price of Deluxe is 10.50
Price of Hawaiian is 11.50

Python

#
# Pizza
#
class Pizza:
    def __init__(self):
        self.price = None
    
    def get_price(self):
        return self.price
        
class HamAndMushroomPizza(Pizza):
    def __init__(self):
        self.price = 8.5
    
class DeluxePizza(Pizza):
    def __init__(self):
        self.price = 10.5
  
class HawaiianPizza(Pizza):
    def __init__(self):
        self.price = 11.5

#
# PizzaFactory
#
class PizzaFactory:
    @staticmethod
    def create_pizza(pizza_type):
        if pizza_type == 'HamMushroom':
            return HamAndMushroomPizza()
        elif pizza_type == 'Deluxe':
            return DeluxePizza()
        elif pizza_type == 'Hawaiian':
            return HawaiianPizza()
 
if __name__ == '__main__':
    for pizza_type in ('HamMushroom', 'Deluxe', 'Hawaiian'):
        print 'Price of {0} is {1}'.format(pizza_type, PizzaFactory.create_pizza(pizza_type).get_price())

PHP

<?php

abstract class Pizza
{
    protected $_price;
    public function getPrice()
    {
        return $this->_price;
    }
}
 
class HamAndMushroomPizza extends Pizza
{
    protected $_price = 8.5;
}
 
class DeluxePizza extends Pizza
{
    protected $_price = 10.5;
}
 
class HawaiianPizza extends Pizza
{
    protected $_price = 11.5;
}
 
class PizzaFactory
{
    public static function createPizza($type)
    {
        $baseClass = 'Pizza';
        $targetClass = ucfirst($type).$baseClass;
        
        if (class_exists($targetClass) && is_subclass_of($targetClass, $baseClass))
            return new $targetClass;
        else
            throw new Exception("The pizza type '$type' is not recognized.");
    }
}

$pizzas = array('HamAndMushroom','Deluxe','Hawaiian');
foreach($pizzas as $p) {
    printf(
        "Price of %s is %01.2f".PHP_EOL ,
        $p ,
        PizzaFactory::createPizza($p)->getPrice()
    );
}


// Output:
// Price of HamAndMushroom is 8.50
// Price of Deluxe is 10.50
// Price of Hawaiian is 11.50

?>

Delphi

program FactoryMethod;

{$APPTYPE CONSOLE}

uses
  SysUtils;

type

// Product
TProduct = class(TObject)
public
  function GetName(): string; virtual; abstract;
end;

// ConcreteProductA
TConcreteProductA = class(TProduct)
public
  function GetName(): string; override;
end;

// ConcreteProductB
TConcreteProductB = class(TProduct)
public
  function GetName(): string; override;
end;

// Creator
TCreator = class(TObject)
public
  function FactoryMethod(): TProduct; virtual; abstract;
end;

// ConcreteCreatorA
TConcreteCreatorA = class(TCreator)
public
  function FactoryMethod(): TProduct; override;
end;

// ConcreteCreatorB
TConcreteCreatorB = class(TCreator)
public
  function FactoryMethod(): TProduct; override;
end;

{ ConcreteProductA }
function TConcreteProductA.GetName(): string;
begin
  Result := 'ConcreteProductA';
end;

{ ConcreteProductB }
function TConcreteProductB.GetName(): string;
begin
  Result := 'ConcreteProductB';
end;

{ ConcreteCreatorA }
function TConcreteCreatorA.FactoryMethod(): TProduct;
begin
  Result := TConcreteProductA.Create();
end;

{ ConcreteCreatorB }
function TConcreteCreatorB.FactoryMethod(): TProduct;
begin
  Result := TConcreteProductB.Create();
end;

const
  Count = 2;

var
  Creators: array[1..Count] of TCreator;
  Product: TProduct;
  I: Integer;

begin
  // An array of creators
  Creators[1] := TConcreteCreatorA.Create();
  Creators[2] := TConcreteCreatorB.Create();

  // Iterate over creators and create products
  for I := 1 to Count do
  begin
    Product := Creators[I].FactoryMethod();
    WriteLn(Product.GetName());
    Product.Free();
  end;

  for I := 1 to Count do
    Creators[I].Free();

  ReadLn;
end.

Uses

See also

References

  1. ^ Gang Of Four
  2. ^ Feathers, Michael (October 2004). Working Effectively with Legacy Code. Upper Saddle River, NJ: Prentice Hall Professional Technical Reference. ISBN 978-0131177055.
  3. ^ Agerbo, Aino (1998). "How to preserve the benefits of design patterns". Conference on Object Oriented Programming Systems Languages and Applications. Vancouver, British Columbia, Canada: ACM: 134–143. ISBN 1-58113-005-8. {{cite journal}}: Unknown parameter |coauthors= ignored (|author= suggested) (help); Unknown parameter |fist= ignored (help)