All Topics  
Factory method pattern

 

   Email Print
   Bookmark   Link






 

Factory method pattern



 
 
The factory method pattern is an object-oriented design pattern
Design pattern (computer science)

In software engineering, a design pattern is a general reusable solution to a commonly occurring problem in software design. A design pattern is not a finished design that can be transformed directly into code ....
. Like other creational pattern
Creational pattern

In software engineering, creational design patterns are design pattern that deal with object lifetime mechanisms, trying to create objects in a manner suitable to the situation....
s, it deals with the problem of creating objects
Object (computer science)

In its simplest embodiment, an object is an allocated region of storage. Since programming languages use variable#Computer_programmings to access objects, the terms object and variable are often used interchangeably....
 (products) without specifying the exact class
Class (computer science)

In object-oriented programming, a class is a programming language construct that is used as a blueprint to create Object s. This blueprint includes Attribute s and Method s that the created objects all share....
 of object that will be created. The factory method design pattern handles this problem by defining a separate method
Method (computer science)

In object-oriented programming, a method is a subroutine that is exclusively associated either with a class or with an object . Like a procedure in procedural programming languages, a method usually consists of a sequence of statement to perform an action, a set of input parameter to customize those actions, and possibly an output value...
 for creating the objects, whose subclasses
Subclass (computer science)

In object-oriented programming, a subclass is a class that Inheritance some properties from its superclass .You can usually think of the subclass as being "a kind of" its superclass, as in a "a Manx is a kind of cat", or "a square is a kind of rectangle":...
 can then override to specify the derived type
Derived type

A derived type is a type given a new type but structurally the same as the original type. The purpose of this type is to create a new type name so that two values can have two distinct types in terms of name....
 of product that will be created. More generally, the term factory method is often used to refer to any method whose main purpose is creation of objects.

The essence of the Factory Pattern
Factory pattern

The factory pattern is a creational design pattern used in software development to encapsulate the processes involved in the creation of objects....
 is to "Define an interface for creating an object, but let the subclasses decide which class to instantiate.






Discussion
Ask a question about 'Factory method pattern'
Start a new discussion about 'Factory method pattern'
Answer questions from other users
Full Discussion Forum



Encyclopedia


The factory method pattern is an object-oriented design pattern
Design pattern (computer science)

In software engineering, a design pattern is a general reusable solution to a commonly occurring problem in software design. A design pattern is not a finished design that can be transformed directly into code ....
. Like other creational pattern
Creational pattern

In software engineering, creational design patterns are design pattern that deal with object lifetime mechanisms, trying to create objects in a manner suitable to the situation....
s, it deals with the problem of creating objects
Object (computer science)

In its simplest embodiment, an object is an allocated region of storage. Since programming languages use variable#Computer_programmings to access objects, the terms object and variable are often used interchangeably....
 (products) without specifying the exact class
Class (computer science)

In object-oriented programming, a class is a programming language construct that is used as a blueprint to create Object s. This blueprint includes Attribute s and Method s that the created objects all share....
 of object that will be created. The factory method design pattern handles this problem by defining a separate method
Method (computer science)

In object-oriented programming, a method is a subroutine that is exclusively associated either with a class or with an object . Like a procedure in procedural programming languages, a method usually consists of a sequence of statement to perform an action, a set of input parameter to customize those actions, and possibly an output value...
 for creating the objects, whose subclasses
Subclass (computer science)

In object-oriented programming, a subclass is a class that Inheritance some properties from its superclass .You can usually think of the subclass as being "a kind of" its superclass, as in a "a Manx is a kind of cat", or "a square is a kind of rectangle":...
 can then override to specify the derived type
Derived type

A derived type is a type given a new type but structurally the same as the original type. The purpose of this type is to create a new type name so that two values can have two distinct types in terms of name....
 of product that will be created. More generally, the term factory method is often used to refer to any method whose main purpose is creation of objects.

Definition

The essence of the Factory Pattern
Factory pattern

The factory pattern is a creational design pattern used in software development to encapsulate the processes involved in the creation of objects....
 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."


Common usage

Factory methods are common in toolkit
Toolkit

Toolkit may refer to an assembly of tools.It may also refer to:* Widget toolkit* Toolkits for User InnovationSpecific toolkits include:...
s
and framework
Framework

A framework is a basic conceptual structure used to solve or address complex issues. This very broad definition has allowed the term to be used as a buzzword, especially in a software context....
s
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
Test-driven development

Test-driven development is a software development technique that uses short development iterations based on pre-written test cases that define desired improvements or new functions....
 to allow classes to be put under test. If such a class Foo creates another object Dangerous that can't be put under automated unit test
Unit test

In computer programming, unit testing is a software design and development method where the programmer gains confidence that individual units of source code are fit for use....
s (perhaps it communicates with a production database that isn't always available, or launches a nuclear missile), then the creation of Dangerous objects is placed in the virtual
Virtual function

In object-oriented programming, a virtual function or virtual method is one whose behavior can be Method overriding within an inheriting class by a function with the same Method signature....
 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 effects 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.

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 thumbnail
Thumbnail

Thumbnails are reduced-size versions of pictures, used to help in recognizing and organizing them, serving the same role for images as a normal text index does for words....
s out of them. The program supports different image formats, represented by a reader class for each format: public interface ImageReader

public class GifReader implements ImageReader

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



The code fragment in the previous example uses a switch statement
Switch statement

In computer programming, a switch statement is a type of control Statement that exists in most modern imperative programming languages . Its purpose is to allow the value of a variable or expression to control the flow of program execution....
 to associate an imageType with a specific factory object
Factory object

In object-oriented computer programming, a factory object is an object for creating other objects. It is an abstraction of a constructor , and can be used to implement various allocation schemes, such as the singleton pattern....
. Alternatively, this association could also be implemented as a mapping. This would allow the switch statement to be replaced with an associative array
Associative array

An associative array is an abstract data type composed of a Collection of unique keys and a collection of values, where each key is associated with one value ....
 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 inheritance.

  • The first limitation is that refactoring an existing class to use factories breaks existing clients. For example, if class Complex were 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 (rather than using the design pattern).

Examples


Java

Pizza example: abstract class Pizza

class HamAndMushroomPizza extends Pizza

class DeluxePizza extends Pizza

class HawaiianPizza extends Pizza

class PizzaFactory

class PizzaLover

C#

Pizza example: public abstract class Pizza

public class HamAndMushroomPizza : Pizza

public class DeluxePizza : Pizza

public class HawaiianPizza : Pizza

// Somewhere in the code ... Console.WriteLine( Pizza.PizzaFactory(Pizza.PizzaType.Hawaiian).GetPrice.ToString("C2") ); // $11.50 ...

private class Pro : Pizza

Console.WriteLine( Pizza.PizzaFactory(Pizza.PizzaType.Hawaiian).GetPrice.ToString("C2") ); // $11.50

C++

Pizza example:
  1. include
  2. include
  3. include // stdauto_ptr
class Pizza ;

class HamAndMushroomPizza: public Pizza ;

class DeluxePizza : public Pizza ;

class HawaiianPizza : public Pizza ;

class PizzaFactory ; //usage int main

JavaScript

Pizza example: //Our pizzas function HamAndMushroomPizza

function DeluxePizza

function HawaiianPizza

//Pizza Factory function PizzaFactory //Usage var pizzaPrice = new PizzaFactory.createPizza("Ham and Mushroom").getPrice; alert(pizzaPrice);

Ruby

Pizza example: class HamAndMushroomPizza def price 8.50 end end

class DeluxePizza def price 10.50 end end

class HawaiianPizza def price 11.50 end end

class ChunkyBaconPizza def price 19.95 end end

class PizzaFactory def create_pizza(style=) case style when 'Ham and Mushroom' HamAndMushroomPizza.new when 'Deluxe' DeluxePizza.new when 'Hawaiian' HawaiianPizza.new when 'WithChunkyBacon' ChunkyBaconPizza.new else DeluxePizza.new end end end

  1. usage
factory = PizzaFactory.new pizza = factory.create_pizza('Ham and Mushroom') pizza.price #=> 8.5
  1. bonus formatting
formatted_price = sprintf("$%.2f", pizza.price) #=> "$8.50"
  1. one liner
sprintf("$%.2f", PizzaFactory.new.create_pizza('Ham and Mushroom').price) #=> "$8.50"

Perl

  1. Our Pizzas


package Pizza; BEGIN; use strict; ################################################## ## Class Pizza ## the object constructor (simplistic version) ## ################################################## sub new ############################################## ## methods to access per-object data## ## ## ## With args, they set the value. Without ## ## any, they only retrieve it/them. ## ############################################## sub getPrice

1; # so the require or use succeeds END;
package HamAndMushroomPizza; BEGIN; use Pizza; @ISA = qw(Pizza); sub getPrice 1; END;
package DeluxePizza; BEGIN use Pizza; @ISA = qw(Pizza); sub getPrice 1; END;
package HawaiianPizza; BEGIN; use Pizza; @ISA = qw(Pizza); sub getPrice 1; END;
package PizzaFactory; BEGIN; ################################################## ## Class PizzaFactory ################################################## sub new sub PizzaType

sub createPizza($PizzaType) 1; # so the require or use succeeds END;
  1. usage
$factory = PizzaFactory->new; $pizza = $factory->PizzaType->HamMushroom; print ($pizza->price); #=> 8.5
  1. bonus formatting
printf("$%.2f", $pizza->getPprice) #=> "$8.50"
  1. one liner
printf("$%.2f", PizzaFactory->createPizza('HamMushroom')->getPrice) #=> "$8.50"

Python

  1. Our Pizzas


class Pizza(object): PIZZA_TYPE_HAM_MUSHROOM, PIZZA_TYPE_DELUXE, PIZZA_TYPE_HAWAIIAN = xrange(3) def __init__(self): self.price = None def getPrice(self): return self.price class HamAndMushroomPizza(Pizza): def __init__(self): self.price = 8.50

class DeluxePizza(Pizza): def __init__(self): self.price = 10.50

class HawaiianPizza(Pizza): def __init__(self): self.price = 11.50

class PizzaFactory(object): def make(self, pizzaType): classByType = return classByType[pizzaType]

  1. Usage
print '$ %.02f' % PizzaFactory.make(Pizza.PIZZA_TYPE_HAM_MUSHROOM).getPrice

Php

// Our Pizzas abstract class Pizza

class HamAndMushroomPizza extends Pizza

class DeluxePizza extends Pizza

class HawaiianPizza extends Pizza

class PizzaFactory // Usage $pizza = PizzaFactorycreate_pizza( 'Hawaiian' ); echo $pizza->get_price;

Haskell

Pizza example: class Pizza a where price a -> Float

data HamMushroom = HamMushroom data Deluxe = Deluxe data Hawaiian = Hawaiian

instance Pizza HamMushroom where price _ = 8.50

instance Pizza Deluxe where price _ = 10.50

instance Pizza Hawaiian where price _ = 11.50

Usage example: main = print (price Hawaiian)

Uses

  • In ADO.NET
    ADO.NET

    ADO.NET is a set of computer software components that can be used by programmers to access data and data services. It is a part of the base class library that is included with the .NET Framework....
    , is an example of the use of factory method to connect parallel class hierarchies.
  • In Qt
    Qt (toolkit)

    Qt is a cross-platform application development framework, widely used for the development of graphical user interface programs , and also used for developing non-GUI programs such as console tools and servers....
    , is a factory method declared in a framework which can be overridden in application code.
  • In Java
    Java (programming language)

    Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java ....
    , several factories are used in the package. e.g. javax.xml.parsers.DocumentBuilderFactory or javax.xml.parsers.SAXParserFactory.


See also

  • Design Patterns
    Design Patterns

    Design Patterns: Elements of Reusable Object-Oriented Software is a software engineering book describing recurring solutions to common problems in software design....
    , the highly-influential book
  • Abstract Factory
    Abstract factory pattern

    A software Design pattern , the Abstract Factory Pattern provides a way to encapsulate a group of individual factory object that have a common theme....
    , a pattern often implemented using factory methods
  • Builder pattern
    Builder pattern

    The Builder Pattern is a software Design pattern . The intention is to abstract steps of construction of object so that different implementations of these steps can construct different representations of objects....
    , another creational pattern
  • Template method pattern
    Template method pattern

    In software engineering, the template method pattern is a software design pattern.It is a so-called behavioral pattern, and is unrelated to template ....
    , which may call factory methods
  • Factory object
    Factory object

    In object-oriented computer programming, a factory object is an object for creating other objects. It is an abstraction of a constructor , and can be used to implement various allocation schemes, such as the singleton pattern....


External links

  • (a Design Description Language)
  • J2EE Pattern Oriented Framework