Khác biệt giữa bản sửa đổi của “Factory method”
Trang mới: thumb|right|300px|Factory method in [[Unified Modeling Language|UML]] [[Image:Factory Method pattern in LePUS3.png|thumb|right|300px|Factory Method in [[Lepu... |
(Không có sự khác biệt)
|
Phiên bản lúc 02:21, ngày 22 tháng 9 năm 2008
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. The factory method design pattern 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.
Definition
The essence of the Factory 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."
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 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.
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 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.
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 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 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 possible), 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 (rather than using the design pattern).
Examples
C#
Pizza example:
public abstract class Pizza
{
public abstract decimal GetPrice();
public enum PizzaType
{
HamMushroom, Deluxe, Seafood
}
public static Pizza PizzaFactory(PizzaType pizzaType)
{
switch (pizzaType)
{
case PizzaType.HamMushroom:
return new HamAndMushroomPizza();
case PizzaType.Deluxe:
return new DeluxePizza();
case PizzaType.Seafood:
return new SeafoodPizza();
}
throw new System.NotSupportedException("The pizza type " + pizzaType.ToString() + " is not recognized.");
}
}
public class HamAndMushroomPizza : Pizza
{
private decimal price = 8.5M;
public override decimal GetPrice() { return price; }
}
public class DeluxePizza : Pizza
{
private decimal price = 10.5M;
public override decimal GetPrice() { return price; }
}
public class SeafoodPizza : Pizza
{
private decimal price = 11.5M;
public override decimal GetPrice() { return price; }
}
// Somewhere in the code
...
Console.WriteLine( Pizza.PizzaFactory(Pizza.PizzaType.Seafood).GetPrice().ToString("C2") ); // $11.50
...
JavaScript
Pizza example:
//Our pizzas
function HamAndMushroomPizza(){
var price = 8.50;
this.getPrice = function(){
return price;
}
}
function DeluxePizza(){
var price = 10.50;
this.getPrice = function(){
return price;
}
}
function SeafoodPizza(){
var price = 11.50;
this.getPrice = function(){
return price;
}
}
//Pizza Factory
function PizzaFactory(){
this.createPizza = function(type){
switch(type){
case "Ham and Mushroom":
return new HamAndMushroomPizza();
case "DeluxePizza":
return new DeluxePizza();
case "Seafood Pizza":
return new SeafoodPizza();
default:
return new DeluxePizza();
}
}
}
//Usage
var pizzaPrice = new PizzaFactory().createPizza("Ham and Mushroom").getPrice();
alert(pizzaPrice);
Ruby
Pizza example:
class HamAndMushroomPizza
def price
8.50
end
end
class DeluxePizza
def price
10.50
end
end
class SeafoodPizza
def price
11.50
end
end
class PizzaFactory
def create_pizza(style='')
case style
when 'Ham and Mushroom'
HamAndMushroomPizza.new
when 'DeluxePizza'
DeluxePizza.new
when 'Seafood Pizza'
SeafoodPizza.new
else
DeluxePizza.new
end
end
end
# usage
factory = PizzaFactory.new
pizza = factory.create_pizza('Ham and Mushroom')
pizza.price #=> 8.5
# bonus formatting
formatted_price = sprintf("$%.2f", pizza.price) #=> "$8.50"
# one liner
sprintf("$%.2f", PizzaFactory.new.create_pizza('Ham and Mushroom').price) #=> "$8.50"
Python
# Our Pizzas
class Pizza:
HAM_MUSHROOM_PIZZA_TYPE = 0
DELUXE_PIZZA_TYPE = 1
SEAFOOD_PIZZA_TYPE= 2
def __init__(self):
self.__price = None
def getPrice(self):
return self.__price
class HamAndMushroomPizza(Pizza):
def __init__(self):
self.__price = 8.50
class DeluxePizza(Pizza):
def __init__(self):
self.__price = 10.50
class SeafoodPizza(Pizza):
def __init__(self):
self.__price = 11.50
class PizzaFactory:
def createPizza(self, pizzaType):
if pizzaType == Pizza.HAM_MUSHROOM_PIZZA_TYPE:
return HamAndMushroomPizza()
elif pizzaType == Pizza.DELUXE_PIZZA_TYPE:
return DeluxePizza()
elif pizzaype == Pizza.SEAFOOD_PIZZA_TYPE:
return SeafoodPizza()
else:
return DeluxePizza()
# Usage
pizzaPrice = PizzaFactory().createPizza(Pizza.HAM_MUSHROOM_PIZZA_TYPE).getPrice()
print "$%.02f" % pizzaPrice
Uses
- In ADO.NET, IDbCommand.CreateParameter is an example of the use of factory method to connect parallel class hierarchies.
- In Qt, QMainWindow::createPopupMenu is a factory method declared in a framework which can be overridden in application code.
- In Java (programming language) several factories are used in the javax.xml.parsers package. e.g. javax.xml.parsers.DocumentBuilderFactory or javax.xml.parsers.SAXParserFactory.
See also
- Design Patterns, the highly-influential book
- Abstract Factory, a pattern often implemented using factory methods
- Builder pattern, another creational pattern
- Template method pattern, which may call factory methods
- Factory object
References
- Fowler, Martin (1999). Refactoring: Improving the Design of Existing Code. Addison-Wesley. ISBN 0-201-48567-2. Đã bỏ qua tham số không rõ
|coauthors=
(gợi ý|author=
) (trợ giúp); Đã bỏ qua tham số không rõ|month=
(trợ giúp) - Gamma, Erich; Helm, Richard; Johnson, Ralph; Vlissides, John (1994). Design Patterns: Elements of Reusable Object-Oriented Software. Addison-Wesley. ISBN 0-201-63361-2.Quản lý CS1: nhiều tên: danh sách tác giả (liên kết)
- Cohen, Tal (2007). “Better Construction with Factories” (PDF). Journal of Object Technology. Bertrand Meyer. Truy cập ngày 12 tháng 3 năm 2007. Đã bỏ qua tham số không rõ
|coauthors=
(gợi ý|author=
) (trợ giúp)
External links
- Factory method in UML and in LePUS3 (a Design Description Language)
- Description from the Portland Pattern Repository
- Jt J2EE Pattern Oriented Framework