简体   繁体   中英

Creation method vs Factory Method

"Kerievsky states that the Replace Constructors with Creation Methods refactoring does not generate an implementation that is fully compliant with the Gang of Four's concept of a Factory Method."

I'm trying to wrap my head around this. As far as I know Factory methods are always Creation methods but Creation Methods are not always Factory methods? Could someone explain this to me?

Well, you can replace the contructors with facotry methods. But to be fully compliant you need to have a class heriacy where

The factory method pattern relies on inheritance, as object creation is delegated to subclasses that implement the factory method to create objects. http://en.wikipedia.org/wiki/Factory_method_pattern

If I understand correctly, what Kerievsky meant is:

  • If we only consider a method which simply creates an object, then Factory and creation method are same.
  • The main difference is the coupling. The main motivation behind creating factory method is to facilitate the loose coupling and differing object creation. Whereas the creation methods are tightly coupled to the class where is defined.

The idea is also explained in the book as follows:

To form a Creation Method, a class must implement a static or nonstatic method that instantiates and returns an object. On the other hand, if you wish to form a Factory Method [DP], you need the following:

• A type (defined by an interface, abstract class, or class) to identify the set of classes that Factory Method implementors may instantiate and return

• The set of classes that implement that type

• Several classes that implement the Factory Method, making local decisions about which of the set of classes to instantiate, initialize, and return

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM