Wednesday, October 28, 2015

Factory method

Factory Method define an interface for creating an object, but let subclasses decide which class to instantiate. It can be considered as a polypmorphic creation method (the principal difference with a polymorphic method is that this one returns an object).





On this example, Creator is an interface implemented in ConcreteCreator. Client will call Creator.factoryMethod(userParam) where userParam is the argument that identifies the object to be created. As we can see, the client is totally decoupled of the implementation details of the derived classes.


Check list

  1. If you have an inheritance hierarchy that exercises polymorphism, consider adding a polymorphic creation capability by defining a static factory method in the base class.
  2. Design the arguments to the factory method. What qualities or characteristics are necessary and sufficient to identify the correct derived class to instantiate?
  3. Consider designing an internal "object pool" that will allow objects to be reused instead of created from scratch.
  4. Consider making all constructors private or protected.

0 comments:

Post a Comment