Design Patterns -- Factory Method

来源:互联网 发布:mysql更新语句怎么写 编辑:程序博客网 时间:2024/04/30 14:13

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:

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:

 and sequence diagram:

原创粉丝点击