The Factor Method pattern lets a class developer define the interface for creating an object while retaining control of which class to instantiate, see pic:
![](http://www.dofactory.com/Patterns/Diagrams/factory.gif)
To summarize, the signs that Factory Method is at work are that an operation:
- Creates a new object
- Returns a type that is an abstract calss or an interface
- The class/interface returned is implemented by several classes (The subclass is to determine which class to instantiate)
The spirit of Factory Method is that the object creator makes a choice about
which of several possible classes to instantiate for the client. In other words, Factory Method lets
subclasses decide which class to instantiate.
The
Iterator in Java is a good example for Factory Method.
The Factory Method pattern often appears when we use
parallel herarchies to model a problem domain. Factory Method lets you connect parallel hiearchies by letting subclasses in one hierarchy determine which class to instantiate in the corresponding hierarchy, see pic:
![](http://www.cnblogs.com/images/cnblogs_com/zhenyulu/Pic41.gif)
and sequence diagram: