Factory method pattern

Factory method pattern
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 creation of an object often requires complex processes not appropriate to include within a composing object. The object's creation may lead to a significant duplication of code, may require information not accessible to the composing object, may not provide a sufficient level of abstraction, or may otherwise not be part of the composing object's concerns. The factory method design pattern handles these problems 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.

Some of the processes required in the creation of an object include determining which object to create, managing the lifetime of the object, and managing specialized build-up and tear-down concerns of the object. 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.

Contents

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]

Concept

In object-oriented computer programming, a factory is an object for creating other objects. It is an abstraction of a constructor, and can be used to implement various allocation schemes. For example, using this definition, singletons implemented by the singleton pattern are formal factories.

A factory object typically has a method for every kind of object it is capable of creating. These methods optionally accept parameters defining how the object is created, and then return the created object.

Factory objects are used in situations where getting hold of an object of a particular kind is a more complex process than simply creating a new object. The factory object might decide to create the object's class (if applicable) dynamically, return it from an object pool, do complex configuration on the object, or other things.

These kinds of objects have proven useful and several design patterns have been developed to implement them in many languages. For example, several "GoF patterns", like the "Factory method pattern", the "Builder" or even the "Singleton" are implementations of this concept. The "Abstract factory pattern" instead is a method to build collections of factories.

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.

Applicability

Use the factory pattern when:

  • The creation of the object precludes reuse without significantly duplicating code.
  • The creation of the object requires access to information or resources not appropriate to contain within the composing object.
  • The lifetime management of created objects needs to be centralised to ensure consistent behavior.

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

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 and VB.NET):

class Complex {
     public static Complex fromCartesian(double real, double imaginary) {
         return new Complex(real, imaginary);
     }
 
     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);


Public Class Complex
    Public Shared Function fromCartesian(real As Double, imaginary As Double) As Complex
        Return (New Complex(real, imaginary))
    End Function
 
    Public Shared Function fromPolar(modulus As Double, angle As Double) As Complex
        Return (New Complex(modulus * Math.Cos(angle), modulus * Math.Sin(angle)))
    End Function
 
    Private Sub New(a As Double, b As Double)
        '...
    End Sub
End Class

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 from 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
{
    public DecodedImage getDecodedImage()
    {
        // ...
        return decodedImage;
    }
}

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.

Example Implementations

Java

A maze game may be played in two modes, one with regular rooms that are only connected with adjacent rooms, and one with magic rooms that allow players to be transported at random (this Java example is similar to one in the book Design Patterns). The regular game mode could use this template method:

public class MazeGame {
  public MazeGame() {
     Room room1 = makeRoom();
     Room room2 = makeRoom();
     room1.connect(room2);
     this.addRoom(room1);
     this.addRoom(room2);
  }
 
  protected Room makeRoom() {
     return new OrdinaryRoom();
  }
}

In the above snippet, makeRoom is a template method. It encapsulates the creation of rooms such that other rooms can be used in a subclass. To implement the other game mode that has magic rooms, it suffices to override the makeRoom method:

public class MagicMazeGame extends MazeGame {
  @Override
  protected Room makeRoom() {
      return new MagicRoom();
  }
}

PHP

class Factory
{
    public static function build($type)
    {
        $class = 'Format' . $type;
        if (!class_exists($class)) {
            throw new Exception('Missing format class.');
        }
        return new $class;
    }
}
 
class FormatString {}
class FormatNumber {}
 
try {
    $string = Factory::build('String');
}
catch (Exception $e) {
    echo $e->getMessage();
}
 
try {
    $number = Factory::build('Number');
}
catch (Exception $e) {
    echo $e->getMessage();
}

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 feasible), 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]

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; Agerbo, Cornils (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. 

External links


Wikimedia Foundation. 2010.

Игры ⚽ Поможем сделать НИР

Look at other dictionaries:

  • Factory Method — Der Begriff Fabrikmethode (englisch Factory Method) bezeichnet ein Entwurfsmuster (engl. Design Pattern) aus dem Bereich der Softwareentwicklung. Das Muster beschreibt, wie ein Objekt durch Aufruf einer Methode anstatt durch direkten Aufruf eines …   Deutsch Wikipedia

  • Method overloading — is a feature found in various programming languages such as Ada, C#, C++ and Java that allows the creation of several functions with the same name which differ from each other in terms of the type of the input and the type of the output of the… …   Wikipedia

  • Factory pattern — See also Factory method pattern The Factory pattern is a creational design pattern used in software development to encapsulate the processes involved in the creation of objects. The creation of an object often requires complex processes not… …   Wikipedia

  • Factory-Pattern — Der Begriff Fabrikmethode (englisch Factory Method) bezeichnet ein Entwurfsmuster (engl. Design Pattern) aus dem Bereich der Softwareentwicklung. Das Muster beschreibt, wie ein Objekt durch Aufruf einer Methode anstatt durch direkten Aufruf eines …   Deutsch Wikipedia

  • Factory Pattern — Der Begriff Fabrikmethode (englisch Factory Method) bezeichnet ein Entwurfsmuster (engl. Design Pattern) aus dem Bereich der Softwareentwicklung. Das Muster beschreibt, wie ein Objekt durch Aufruf einer Methode anstatt durch direkten Aufruf eines …   Deutsch Wikipedia

  • Factory (disambiguation) — A factory is a large industrial building where goods are manufactured. The word can be traced back to the Latin factorium , which is literally a place of making (producing) .Factory may also refer to: * Factory (trading post), officially licensed …   Wikipedia

  • 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.A factory object… …   Wikipedia

  • Abstract factory pattern — The abstract factory pattern is a software design pattern that provides a way to encapsulate a group of individual factories that have a common theme. In normal usage, the client software creates a concrete implementation of the abstract factory… …   Wikipedia

  • Singleton pattern — In software engineering, the singleton pattern is a design pattern used to implement the mathematical concept of a singleton, by restricting the instantiation of a class to one object. This is useful when exactly one object is needed to… …   Wikipedia

  • Design Pattern — Patron de conception Pour les articles homonymes, voir Patron. Un patron de conception (design pattern en anglais) est un concept de génie logiciel destiné à résoudre les problèmes récurrents suivant le paradigme objet. En français on utilise… …   Wikipédia en Français

Share the article and excerpts

Direct link
Do a right-click on the link above
and select “Copy Link”