Factory method pattern: Difference between revisions

Content deleted Content added
Rewrote article
Line 1:
The '''Factory Method pattern''' is an [[object-oriented]] [[design pattern (computer science)|design pattern]].
In [[computer programming]], the '''factory method pattern''' is a [[software design pattern]]. The factory method pattern is useful to solve the common problem of constructing [[object (computer science)|objects]] based on some [[input]] such that [[function (programming)|function]]s inside the objects depend upon the input.
Like other [[creational pattern]]s, it deals with the problem of [[creating]] [[object (computer science)|object]]s (products) without specifying the exact [[class (computer science)|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 (computer science)|method]] for creating the objects, which [[subclass (computer science)|subclass]]es can then override to specify the 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.
 
==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 achive 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.
 
==Example==
Consider a database frontend that supports many different data types.
Fields in the database are represented by 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.
Consider as an example a [[class (computer science)|class]] to read [[image file]]s and make [[thumbnail]]s out of them. This can be solved by bundling them all into one class and deciding which bit of code to run:
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, but a BooleanField should be displayed as a checkbox.
 
To solve this, Field contains a factory method, createControl(), that is called from display() to get a control of the correct type.
===A bad solution===
 
public class ImageReaderControl {
privatepublic intvoid fileType;display() {
private String fileContents; // ...
}
private byte[] decodedImage;
// ...
}
class TextBox : Control {
public ImageReader( InputStream in ) {
// ...
// Figure out what type of file this input stream represents
}
// (eg gif, jpeg, png, tif, etc )
class CheckBox : Control {
this.fileType = fileType;
// decodeFile();...
}
abstract class Field {
public void display() {
Control c = createControl();
c.display();
}
public abstract Control createControl();
private void decodeFile() {
}
switch( fileType ) {
case ImageReader.GIF:
class TextField : Field {
// do gif decoding (many lines)
private string breakvalue;
case ImageReader.JPEG:
public Control createControl() {
// do jpeg decoding (many lines)
TextBox t = new breakTextBox();
case ImageReadert.PNG:setText(this.value);
return t;
// do png decoding (many lines)
break;}
}
// etc...
}
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 subclass the creator and TextBox and CheckBox are subclasses of product.
This method has the advantage of abstracting the [[file type]] from the class that calls this ImageReader, but as the number of file types supported gets larger, the code will quickly become huge, unwieldy and hard to maintain.
 
==Common usage==
*Factory Methods are common in [[toolkit]]s and [[framework]]s 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 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.
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)
 
===Encapsulation===
===A better, but not perfect, solution===
Factory methods encapsulate the creation of objects.
This can be useful if the creation process is complex, for example if it depends on settings in configuration files or on user input.
 
Consider as an example a program to read [[image file]]s and make [[thumbnail]]s out of them.
Another solution that seems possible is to have a separate object for each of these file types:
The program supports different image formats, represented by a reader class for each format:
 
public interface ImageReader {
Line 61 ⟶ 125:
}
Each time the program reads an image it needs to create a reader of the appropriate type based on some information in the file.
// Then you would use them as:
This logic can be encapsulated in a factory method:
public class MyProg {
public static void main( String[] args ) {
String filename = args[0];
ImageReader out;
if( endsInDotGif( filename )) {
out = new GifReader( fileInputStream );
}
if( endsInDotJpeg( filename )) {
out = new JpegReader( fileInputStream );
}
printOut( out.getDecodedImage );
}
}
 
Again, there are advantages to this method (clean organisation of the ImageReader classes, the code being split up in several classes), but this is at the cost of the abstraction of the image type. Again, when dozens of file types need to be supported, this will be unsatisfactory and produce code that is hard to maintain.
 
===Using the factory pattern===
 
The factory pattern can be used instead to combine the better parts of the above solutions. The factory is a class that returns another class depending on the context. So in this situation, keeping the separate [[class design]] as in the last example:
 
public class ImageReaderFactory {
Line 93 ⟶ 134:
switch( imageType ) {
case ImageReaderFactory.GIF:
GifReader r =return new GifReader( is );
return (ImageReader)r;
break;
case ImageReaderFactory.JPEG:
JpegReader r =return new JpegReader( is );
return (ImageReader)r;
break;
// etc.
}
Line 108 ⟶ 145:
 
==See also==
===Related design patterns===
* [[ClassFactory]]
* [[Abstract factory pattern|Abstract Factory]] (When the– objectoften hasimplemented nousing descriptiveFactory attributes)Methods.
*[[Template method pattern|Template Method]] – may call factory methods.
* [[Interpreter pattern]] (When a language is used to describe the objects)
 
==References==
*{{Book reference |
Author=[[Martin Fowler|Fowler, Martin]] |
Title=Refactoring: Improving the Design of Existing Code |
Publisher=Addison-Wesley |
Year=1999 |
ID=ISBN 0-201-48567-2
}}
*{{Book reference |
Author=[[Erich Gamma|Gamma, Erich]]; [[Richard Helm|Helm, Richard]]; Johnson, Ralph; Vlissides, John |
Title=[[Design Patterns|Design Patterns: Elements of Reusable Object-Oriented Software]] |
Publisher=Addison-Wesley |
Year=1994 |
ID=ISBN 0-201-63361-2
}}
 
==External links==
*[http://www.mode-x.com/index.php?id=24 mode-x.com] (contributed by author)
*[http://c2.com/cgi/wiki?FactoryMethodPattern Description from the Portland Pattern Repository]
*[http://www.refactoring.com/catalog/replaceConstructorWithFactoryMethod.html Refactoring: Replace Constructor with Factory Method]
 
===Uses of Factory Method===
*In [[ADO.NET]], [http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemdataidbcommandclasscreateparametertopic.asp IDbCommand.CreateParameter] is an example of the use of Factory Method to connect parallel class hierarchies.
*In [[Qt]], [http://doc.trolltech.com/4.0/qmainwindow.html#createPopupMenu QMainWindow::createPopupMenu] is a factory method declared in a framework which can be overridden in application code.
 
[[Category:Software design patterns]]