Factory method in UML
Factory Method in LePUS3

The factory method pattern is an object-oriented design pattern. 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, whose subclasses can then override to specify the derived type 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.

Contents

Definition

The essence of the Factory 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."

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.

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 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 GifReader( InputStream in ) 
     {
         // check that it's a gif, throw exception if it's not, then if it is
         // decode it.
     }
 
     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 = figureOutImageType( is );
 
        switch( imageType ) 
        {
            case ImageReaderFactory.GIF:
                return new GifReader( is ); break ;
            case ImageReaderFactory.JPEG:
                return new JpegReader( is ); break ;
            // 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 inheritance.

  • 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 (rather than using the design pattern).

Examples

C#

Pizza example:

public abstract class Pizza
{
    public abstract decimal GetPrice();
 
    public enum PizzaType
    {
        HamMushroom, Deluxe, Hawaiian
    }
    public static Pizza PizzaFactory(PizzaType pizzaType)
    {
        switch (pizzaType)
        {
            case PizzaType.HamMushroom:
                return new HamAndMushroomPizza();
 
            case PizzaType.Deluxe:
                return new DeluxePizza();
 
            case PizzaType.Hawaiian:
                return new HawaiianPizza();
 
        }
 
        throw new System.NotSupportedException("The pizza type " + pizzaType.ToString() + " is not recognized.");
    }
}
public class HamAndMushroomPizza : Pizza
{
    private decimal price = 8.5M;
    public override decimal GetPrice() { return price; }
}
 
public class DeluxePizza : Pizza
{
    private decimal price = 10.5M;
    public override decimal GetPrice() { return price; }
}
 
public class HawaiianPizza : Pizza
{
    private decimal price = 11.5M;
    public override decimal GetPrice() { return price; }
}
 
// Somewhere in the code
...
  Console.WriteLine( Pizza.PizzaFactory(Pizza.PizzaType.Hawaiian).GetPrice().ToString("C2") ); // $11.50
...
 
 
 
<pro>
 
private class Pro : Pizza
 
Console.WriteLine( Pizza.PizzaFactory(Pizza.PizzaType.Hawaiian).GetPrice().ToString("C2") ); // $11.50

C++

Pizza example:

#include <string>
#include <iostream>
#include <memory> // std::auto_ptr
class Pizza {
public:
    virtual void get_price() const = 0;
    virtual ~Pizza() {};
};
 
class HamAndMushroomPizza: public Pizza {
public:
    virtual void get_price() const {
        std::cout << "Ham and Mushroom: $8.5" << std::endl;
    }
};
 
class DeluxePizza : public Pizza {
public:
    virtual void get_price() const {
        std::cout << "Deluxe: $10.5" << std::endl;
    }
};
 
class HawaiianPizza : public Pizza {
public:
    virtual void get_price() const {
        std::cout << "Hawaiian: $11.5" << std::endl;
    }
};
 
class PizzaFactory {
public:
    static Pizza* create_pizza(const std::string& type) {
        if (type == "Ham and Mushroom")
            return new HamAndMushroomPizza();
        else if (type == "Hawaiian")
            return new HawaiianPizza();
        else
            return new DeluxePizza();
    }
};
//usage
int main() {
    PizzaFactory factory;
 
    std::auto_ptr<const Pizza> pizza(factory.create_pizza("Default"));
    pizza->get_price();
 
    pizza.reset(factory.create_pizza("Ham and Mushroom"));
    pizza->get_price();
 
    pizza.reset(factory.create_pizza("Hawaiian"));
    pizza->get_price();
}

JavaScript

Pizza example:

//Our pizzas
function HamAndMushroomPizza(){
  var price = 8.50;
  this.getPrice = function(){
    return price;
  }
}
 
function DeluxePizza(){
  var price = 10.50;
  this.getPrice = function(){
    return price;
  }
}
 
function HawaiianPizza(){
  var price = 11.50;
  this.getPrice = function(){
    return price;
  }
}
 
//Pizza Factory
function PizzaFactory(){
  this.createPizza = function(type){
     switch(type){
      case "Ham and Mushroom":
        return new HamAndMushroomPizza();
      case "Hawaiian":
        return new HawaiianPizza();
      default:
          return new DeluxePizza();
     }     
  }
}
 
//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 PizzaFactory
  def create_pizza(style='')
    case style
      when 'Ham and Mushroom'
        HamAndMushroomPizza.new
      when 'Deluxe'
        DeluxePizza.new
      when 'Hawaiian'
        HawaiianPizza.new
      else
        DeluxePizza.new
    end   
  end
end
 
# usage
factory = PizzaFactory.new
pizza = factory.create_pizza('Ham and Mushroom')
pizza.price #=> 8.5
# bonus formatting
formatted_price = sprintf("$%.2f", pizza.price) #=> "$8.50"
# one liner
sprintf("$%.2f", PizzaFactory.new.create_pizza('Ham and Mushroom').price) #=> "$8.50"


Python

# 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 = {
            Pizza.PIZZA_TYPE_HAM_MUSHROOM: HamAndMushroomPizza,
            Pizza.PIZZA_TYPE_DELUXE: DeluxePizza,
            Pizza.PIZZA_TYPE_HAWAIIAN: HawaiianPizza,
        }
        return classByType[pizzaType]() if pizzaType in classByType else DeluxePizza()
 
# Usage
print '$ %.02f' % PizzaFactory().make(Pizza.PIZZA_TYPE_HAM_MUSHROOM).getPrice()

Uses

See also

References

External links


No comments have been added.



Your name:

City:

Country:

Your comments:

Security check *
(Please enter the number into adjoining box)