Thursday 30 November 2017

Factory Design Pattern


Motivation
The Factory Design Pattern is probably the most used design pattern in modern programming languages like Java and C#. It comes in different variants and implementations. If you are searching for it, most likely, you'll find references about the GoF patterns: Factory Method and Abstract Factory.

Intent
creates objects without exposing the instantiation logic to the client.
refers to the newly created object through a common interface

Where to use
Factory pattern should be used when: - a framework delegate the creation of objects derived from a common superclass to the factory - we need flexibility in adding new types of objects that must be created by the class

Common Usage
Along with singleton pattern the factory is one of the most used patterns. Almost any application has some factories. Here are a some examples in java:
- factories providing an xml parser: javax.xml.parsers.DocumentBuilderFactory or javax.xml.parsers.SAXParserFactory
- java.net.URLConnection - allows users to decide which protocol to use.

Applicability
Use the Factory Method pattern when 1. a class can't anticipate the class of objects it must create. 2. a class wants its subclasses to specify the objects it creates. 3. classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate.

Benefit(s)
1. Provides hooks for subclasses.
2. Connects parallel class hierarchies.

Disadvantage(s)
A potential disadvantage of factory methods is that clients might have to subclass the Creator class just to create a particular ConcreteProduct object. Subclassing is fine when the client has to subclass the Creator class anyway, but otherwise the client now must deal with another point of evolution.


Happy Learning.

1 comment: