Factory method pattern

From Wikipedia, the free encyclopedia

Jump to: navigation, search
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

[edit] 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."

[edit] 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[1]. 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 effects of using a real Dangerous object.

[edit] 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.

[edit] 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 = figureOutImageType( 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.

[edit] 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).[citation needed]

[edit] Examples

[edit] Java

Pizza example:

abstract class Pizza {
    public abstract double getPrice();
}
 
class HamAndMushroomPizza extends Pizza {
    private double price = 8.5;
 
    public double getPrice() {
        return price;
    }
}
 
class DeluxePizza extends Pizza {
    private double price = 10.5;
 
    public double getPrice() {
        return price;
    }
}
 
class HawaiianPizza extends Pizza {
    private double price = 11.5;
 
    public double getPrice() {
        return price;
    }
}
 
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());
        }
    }
}

[edit] 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();
                break;
 
            case PizzaType.Deluxe:
                return new DeluxePizza();
                break;
 
            case PizzaType.Hawaiian:
                return new HawaiianPizza();
                break;
 
            default:
                break;
        }
 
        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

[edit] 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();
}

[edit] 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);

[edit] 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
 
# 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"

[edit] Perl

#!/usr/bin/env perl
package Pizza;
use Moose;
 
has price => (is => 'rw', isa => 'Num');
 
package HamAndMushroomPizza;
use Moose;
extends 'Pizza';
 
sub BUILD {
    shift->price(8.5)
}
 
package DeluxePizza;
use Moose;
extends 'Pizza';
 
sub BUILD {
    shift->price(10.5)
}
 
package HawaiianPizza;
use Moose;
extends 'Pizza';
 
sub BUILD {
    shift->price(11.5)
}
 
package PizzaFactory;
use Moose;
 
sub createPizza {
    my $pizza_type = shift;
    my $pizza = eval "${pizza_type}Pizza->new()";
    confess "Pizza not found" if ($@);
    return $pizza;
}
 
 
# The following prints them all:
package main;
use strict;
use feature ':5.10';
 
my @pizza_types = qw/HamAndMushroom Deluxe Hawaiian/;
 
for my $pizza_type (@pizza_types) {
    my $pizza = PizzaFactory::createPizza($pizza_type);
    say "Price of $pizza_type is " . $pizza->price();
}

[edit] Python

# Our Pizzas
 
class Pizza(object):
    PIZZA_TYPE_HAM_MUSHROOM, PIZZA_TYPE_DELUXE, PIZZA_TYPE_HAWAIIAN = range(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]()
 
# Usage
print ('$ %.02f' % PizzaFactory().make(Pizza.PIZZA_TYPE_HAM_MUSHROOM).getPrice())

[edit] Php

// Our Pizzas
abstract class Pizza {
    abstract public function get_price();
}
 
class HamAndMushroomPizza extends Pizza {
    public function get_price() {
        return 8.5;
    }
}
 
class DeluxePizza extends Pizza {
    public function get_price() {
        return 10.5;
    }
}
 
class HawaiianPizza extends Pizza {
    public function get_price() {
        return 11.5;
    }
}
 
class PizzaFactory {
    public static function create_pizza( $type ) {
        switch( $type ) {
            case 'Ham and Mushroom':
                return new HamAndMushroomPizza();
            case 'Hawaiian':
                return new HawaiianPizza();
            default:
                return new DeluxePizza();
        }
    }
}
// Usage
$pizza = PizzaFactory::create_pizza( 'Hawaiian' );
echo $pizza->get_price();

[edit] Haskell

This example uses Haskell's type classes rather than object-oriented classes (which are not supported in Haskell).

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)

[edit] Uses

[edit] See also

[edit] References

  1. ^ Feathers, Michael (October 2004). Working Effectively with Legacy Code. ISBN 978-0131177055. 

[edit] External links

Personal tools