Описание тега factory-method
The Factory Method Pattern represents a virtual constructor. The canonical example from the GoF book is a framework for applications that present multiple documents. The framework handles document creation, but the type of document varies for each concrete application using the framework. In other words, the framework, (page 107)
...only knows when a new document should be created, not what kind of Document to create. This creates a dilemma: The framework must instantiate classes, but it only knows about abstract classes, which it cannot instantiate.
The Factory Method pattern offers a solution. It encapsulates the knowledge of which Document subclass to create and moves this knowledge out of the framework.
The pattern is implemented by four participants. (page 108)
- Product (Document) - defines the interface of objects the factory method creates.
- ConcreteProduct (MyDocument) - implements the
Product
interface.- Creator (Application) - declares the factory method, which returns an object of type
Product
.- ConcreteCreator (MyApplication) - overrides the factory method to return an instance of a
ConcreteProduct
.
The Gang of Four offer the following criteria for applying the Factory Method Pattern.
Use the Factory Method pattern when
- a class can't anticipate the class of objects it must create.
- a class wants its subclasses to specify the objects it creates.
- classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate.
The pattern has several variants. (page 110)
- The two main variations of the Factory Method pattern are (1) the case when the
Creator
class is an abstract class and does not provide an implementation for the factory method it declares, and (2) the case when theCreator
is a concrete class and provides a default implementation for the factory method.- Another variation on the pattern lets the factory method create multiple kinds of products. The factory method takes a parameter that identifies the kind of object to create. All objects the factory method creates will share the
Product
interface.
See Factory Method for a longer summary of the GoF book.
Note the Gang of Four published two different factory patterns, the other being abstract-factory. Additionally, there are factory patterns outside the GoF book, so the term "factory" by itself is ambiguous.