Factory method pattern

Factory method pattern

From Wikipedia, the free encyclopedia

 
Factory method in UML
Factory method in UML
Factory Method in LePUS3
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, which 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.

 

<script type=text/javascript> // </script>

 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 );
            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 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 Types
    {
        HamMushroom, Deluxe, Seafood
    }
    public static Pizza PizzaFactory(Types t)
    {
        switch (t)
        {
            case Types.HamMushroom:
                return new HamAndMushroomPizza();
 
            case Types.Deluxe:
                return new DeluxePizza();
 
            case Types.Seafood:
                return new SeafoodPizza();
 
        }
 
        throw new System.NotSupportedException("The pizza type " + t.ToString() + " is not recognized.");
    }
}
public class HamAndMushroomPizza : Pizza
{
    private decimal m_Price = 8.5M;
    public override decimal GetPrice() { return m_Price; }
}
 
public class DeluxePizza : Pizza
{
    private decimal m_Price = 10.5M;
    public override decimal GetPrice() { return m_Price; }
}
 
public class SeafoodPizza : Pizza
{
    private decimal m_Price = 11.5M;
    public override decimal GetPrice() { return m_Price; }
}
 
// Somewhere in the code
...
  Console.WriteLine( Pizza.PizzaFactory(Pizza.Types.Seafood).GetPrice().ToString("C2") ); // $11.50
...

 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 SeafoodPizza(){
  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 "DeluxePizza":
        return new DeluxePizza();
      case "Seafood Pizza":
        return new SeafoodPizza();
      default:
          return new DeluxePizza();
     }     
  }
}
 
//Usage
var pizzaPrice = new PizzaFactory().createPizza("Ham and Mushroom").getPrice();
alert(pizzaPrice);

Python

    """
    A generic factory implementation.
    Examples:
    >>f=Factory()
    >>class A:pass
    >>f.register("createA",A)
    >>f.createA()
    <__main__.A instance at 01491E7C>
 
    >>> class B:
    … def __init__(self, a,b=1):
    … self.a=a
    … self.b=b
    …
    >>> f.register("createB",B,1,b=2)
    >>> f.createB()
    >>> b=f.createB()
    >>>
    >>> b.a
    1
    >>> b.b
    2
 
    >>> class C:
    … def __init__(self,a,b,c=1,d=2):
    … self.values = (a,b,c,d)
    …
    >>> f.register("createC",C,1,c=3)
    >>> c=f.createC(2,d=4)
    >>> c.values
    (1, 2, 3, 4)
 
    >>> f.register("importSerialization",__import__,"cPickle")
    >>> pickle=f.importSerialization()
    >>> pickle
    <module 'cPickle' (built-in)>
    >>> f.register("importSerialization",__import__,"marshal")
    >>> pickle=f.importSerialization()
    >>> pickle
    <module 'marshal' (built-in)>
 
    >>> f.unregister("importSerialization")
    >>> f.importSerialization()
    Traceback (most recent call last):
    File "<interactive input>", line 1, in ?
    AttributeError: Factory instance has no attribute 'importSerialization'
    """
 
    from functools import partial, wraps
 
    class Factory:      
        def register(self, methodName, constructor, *args, **kwds):
           """register a constructor"""
           _args = [constructor]
           _args.extend(args)
           setattr(self, methodName, wraps(methodName)(partial(Functor,*_args, **kwds)))
 
        def unregister(self, methodName):
           """unregister a constructor"""
           delattr(self, methodName)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值