Factory method pattern

From Wikipedia, the free encyclopedia

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 creation of objects.

Contents

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

[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] 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 ):

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.

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

[edit] Limitations

There are three limitations associated with the use of the factory method. The first relates to refactoring existing code; the other two relates 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 above). 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, and with the exact same signature. 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 can be alleviated by making factories first-class class members rather than using the design pattern. [1]

[edit] Uses

[edit] See also

[edit] References

[edit] External links