Factory Method Pattern (Head First DP)

Code UP Close:
A factory method handles object creation and encapsulates it in a subclass. This decouples the client code in the superclass from
the object creation code in the subclass.

abstract Product factoryMethod(String type)

A factory method is abstract so the subclass are counted on to handle object creation
A factor method returns a Product that is typically used within methods defined in the superclass
A factory method isolates the client ( the code in the superclass, like orderPizza()) from knowing what kind of concrete Product is actually created

Formal definition of Factory Method Pattern: (Page 134)

        The Factory Method Patterndefi nes an interface for creating an object, but lets subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclass

As with every factory, the Factory Method Pattern gives us a way to encapsulate the instantiations of concrete types. The abstract Creator gives you an interface with a method for creating objects, also known as the “factory method.” Any other methods implemented in the abstract Creator are written to operate on products produced by the factory method.

The creator is a class that contains the implementation for all of the methods to manipulate products, except for the factory method; The abstract factoryMethod() is what all Creator subclasses must implement.

Only subclasses actually implement the factory method and create products.Only subclass (concreatCreator) is responsible for creating one or more concrete products. It is the only class that has the knowledge of how to create these products.

As in the official definition, you’ll often hear developers say that the Factory Method lets subclasses decide which class to instantiate. They say “decides” not because the pattern allows subclasses themselves to decide at runtime, but because the creator class is written without knowledge of the actual products that will be created, which is decided purely by the choice of the subclass that is used.

 

Another design principle (Dependency Inversion Principle):

Depend upon abstractions. Do not  depend upon concrete classes.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s