Content deleted Content added
Rewrote article |
|||
Line 1:
The '''Factory Method pattern''' is an [[object-oriented]] [[design pattern (computer science)|design pattern]].
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.
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.
}
// ...
}
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
public Control createControl() {
TextBox t = new
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 subclass the creator and TextBox and CheckBox are subclasses of product.
==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===
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.
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.
This logic can be encapsulated in a factory method:
public class ImageReaderFactory {
Line 93 ⟶ 134:
switch( imageType ) {
case ImageReaderFactory.GIF:
case ImageReaderFactory.JPEG:
// etc.
}
Line 108 ⟶ 145:
==See also==
===Related design patterns===
*
*[[Template method pattern|Template Method]] – may call factory methods.
==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://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]]
|