Factory Method Pattern
Factory pattern is one of
most used design pattern in Java. This type of design pattern comes under
creational pattern as this pattern provides one of the best ways to create an
[Define an interface for
creating an object, but let the subclasses decide which class to instantiate.
The Factory method lets a class defer instantiation to subclasses. ]
Method Pattern Definition Diagram:
Here we create a Shape
interface and concrete classes implementing the Shape interface. A factory
class ShapeFactory is defined.
is our demo class, it will use ShapeFactory to get a Shape object. It will pass
information (CIRCLE /
RECTANGLE / SQUARE)
to ShapeFactory to get the type of object it needs.
Where Would I Use This Pattern?
behind the Factory Method pattern is that it allows for the case where a client
doesn't know what concrete classes it will be required to create at runtime,
but just wants to get a class that will do the job. The FactoryMethod builds on
the concept of a simple Factory, but lets the subclasses decide which
implementation of the concrete class to use. You'll see factories used in
logging frameworks, and in a lot of scenarios where the client doesn't need to
know about the concrete implementations. It's a good approach to encapsulation.