Factory method pattern

From Free net encyclopedia

(Redirected from Factory method)

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. Factory Method, one of the patterns from the Design Patterns book, 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 to create objects.

Contents

Structure

The main classes in the Factory Method pattern are the creator and the product. The creator needs to create instances of products, but the concrete type of product should not be hardcoded in the creator – subclasses of creator should be able to specify subclasses of product to use.

To achieve this an abstract method (the factory method) is defined on the creator. This method is defined to return a product. Subclasses of creator can override this method to return instances of appropriate subclasses of product.

Image:FactoryMethod.png

Example

Consider a database frontend that supports many different data types. Fields in the database are represented by the abstract class Field. Each supported data type is mapped to a subclass of Field, for example TextField, NumberField, DateField or BooleanField.

Class Field has a method display() for displaying the contents of the field on a window system. Typically one control is created for each field, but the type of control should depend on the type of the field, for example a TextField should be displayed as a textbox control, but a BooleanField should be displayed as a checkbox control.

To solve this, Field contains a factory method, createControl(), that is called from display() to get a control of the correct type.

class Control {
    public void display() {
        // ...
    }
    // ...
}

class TextBox : Control {
    // ...
}

class CheckBox : Control {
    // ...
}

abstract class Field {
    public void display() {
        Control c = createControl();
        c.display();
    }

    public abstract Control createControl();
}

class TextField : Field {
    private string value;

    public Control createControl() {
        TextBox t = new TextBox();
        t.setText(this.value);
        return t;
    }
}

class BooleanField : Field {
    private boolean value;

    public Control createControl() {
        CheckBox c = new CheckBox();
        c.setChecked(this.value);
        return c;
    }
}

In this case, Field is the creator, Control is the product, createControl() is the factory method, TextField and BooleanField are subclasses of the creator and TextBox and CheckBox are subclasses of product.

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 don't 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.

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:

class Complex {
    public static Complex fromCartesian(double real, double imag) {
        return new Complex(real, imag);
    }

    public static Complex fromPolar(double rho, double theta) {
        return new Complex(rho * cos(theta), rho * sin(theta));
    }
 
    private Complex(double a, double b) {
        //...
    }
}
 
Complex c = Complex.fromPolar(1, pi); // Same as fromCartesian(-1, 0)

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 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 combination of a type code and its associated specific factory object can be stored in a map. The switch statement can be avoided to create an extensible factory by a mapping.

See also

Related design patterns

References

External links

Uses of Factory Method

es:Factory Method (patrón de diseño) ru:Factory Method