Builder Design Pattern

Download the working example demo code in java from my GIT repository –https://github.com/premaseem/designPatterns/tree/4bb9beca7bab5b5e71d02b76e4f1ad48fce4aca6/ZipDownloadableProjects

Code Example : Meal builder project examples gives the insight of builder pattern. Typically when we order a meal in lets say Mc Donald – they follow few processes before delivering the actual meal. On example a meal consists of a burger and a cold drink wrapped up in a packet. so input format and out come are same but product is different. Say some time its Veg burger, other times it is chicken burger.

Design Proverb :
A baby is born , however a body builder is created with correct diet and exercise. This the main difference between factory pattern and builder Smile 

When we have a complex object creation then we use builder creational design pattern. On high level it is combination of Factory and Template method design pattern. Factory does not have lot of logic or steps to follow while creation of an object, however builder does have. Builder pattern is used to construct a complex object step by step and the final step will return the object. The process of constructing an object should be generic so that it can be used to create different representations of the same object.

In builder pattern emphasis is on ‘step by step’. Builder pattern will have many number of small steps. Those every steps will have small units of logic enclosed in it. There will also be a sequence involved. It will start from step 1 and will go on upto step n and the final step is returning the object. In these steps, every step will add some value in construction of the object. That is you can imagine that the object grows stage by stage. Builder will return the object in last step.

Intent
  • Separate the construction of a complex object from its representation so that the same construction process can create different representations.
  • Parse a complex representation, create one of several targets.
Problem

An application needs to create the elements of a complex aggregate. The specification for the aggregate exists on secondary storage and one of many representations needs to be built in primary storage.

Discussion

Separate the algorithm for interpreting (i.e. reading and parsing) a stored persistence mechanism (e.g. RTF files) from the algorithm for building and representing one of many target products (e.g. ASCII, TeX, text widget). The focus/distinction is on creating complex aggregates.

The “director” invokes “builder” services as it interprets the external format. The “builder” creates part of the complex object each time it is called and maintains all intermediate state. When the product is finished, the client retrieves the result from the “builder”.

Affords finer control over the construction process. Unlike creational patterns that construct products in one shot, the Builder pattern constructs the product step by step under the control of the “director”.

 

Example

The Builder pattern separates the construction of a complex object from its representation so that the same construction process can create different representations. This pattern is used by fast food restaurants to construct children’s meals. Children’s meals typically consist of a main item, a side item, a drink, and a toy (e.g., a hamburger, fries, Coke, and toy dinosaur). Note that there can be variation in the content of the children’s meal, but the construction process is the same. Whether a customer orders a hamburger, cheeseburger, or chicken, the process is the same. The employee at the counter directs the crew to assemble a main item, side item, and toy. These items are then placed in a bag. The drink is placed in a cup and remains outside of the bag. This same process is used at competing restaurants.

Example of Builder

Check list
  1. Decide if a common input and many possible representations (or outputs) is the problem at hand.
  2. Encapsulate the parsing of the common input in a Reader class.
  3. Design a standard protocol for creating all possible output representations. Capture the steps of this protocol in a Builder interface.
  4. Define a Builder derived class for each target representation.
  5. The client creates a Reader object and a Builder object, and registers the latter with the former.
  6. The client asks the Reader to “construct”.
  7. The client asks the Builder to return the result.
Rules of thumb
  • Sometimes creational patterns are complementory: Builder can use one of the other patterns to implement which components get built. Abstract Factory, Builder, and Prototype can use Singleton in their implementations.
  • Builder focuses on constructing a complex object step by step. Abstract Factory emphasizes a family of product objects (either simple or complex). Builder returns the product as a final step, but as far as the Abstract Factory is concerned, the product gets returned immediately.
  • Builder often builds a Composite.
  • Often, designs start out using Factory Method (less complicated, more customizable, subclasses proliferate) and evolve toward Abstract Factory, Prototype, or Builder (more flexible, more complex) as the designer discovers where more flexibility is needed.

Prototype Design Pattern

Download the working example demo code in java from my GIT repository –https://github.com/premaseem/designPatterns/tree/4bb9beca7bab5b5e71d02b76e4f1ad48fce4aca6/ZipDownloadableProjects

Code Example
The Prototype pattern specifies the kind of objects to create using a prototypical instance. Cell is the abstract class with different subclasses like singleCell Organism, amoeba, bacteria etc. For each sub class a breeder object is created before hand and registered in SpecimenCache.java class. Now whenever client program wants to breed or culture a particular organism say amobea they will fetch it from cache and invoke split/clone method which will provide replicated organism with same state property. Download the example code and have fun.
 Example of Prototype

When creating an object is time consuming and a costly affair and you already have a most similar object instance in hand, then you go for prototype pattern. Instead of going through a time consuming process to create a complex object, just copy the existing similar object and modify it according to your needs. Clone the existing instance in hand and then make the required update to the cloned instance so that you will get the object you need. Other way is, tweak the cloning method itself to suit your new object creation need.

Intent
Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.
  • Co-opt one instance of a class for use as a breeder of all future instances.
  • The new operator considered harmful.
Problem
Application “hard wires” the class of object to create in each “new” expression.
Discussion
Declare an abstract base class that specifies a pure virtual “clone” method, and, maintains a dictionary of all “cloneable” concrete derived classes. Any class that needs a “polymorphic constructor” capability: derives itself from the abstract base class, registers its prototypical instance, and implements the clone() operation.

The client then, instead of writing code that invokes the “new” operator on a hard-wired class name, calls a “clone” operation on the abstract base class, supplying a string or enumerated data type that designates the particular concrete derived class desired.

Prototype Design Pattern

Check list
Add a clone() method to the existing “product” hierarchy.
  1. Design a “registry” that maintains a cache of prototypical objects. The registry could be encapsulated in a new Factory class, or in the base class of the “product” hierarchy.
  2. Design a factory method that: may (or may not) accept arguments, finds the correct prototype object, calls clone() on that object, and returns the result.
  3. The client replaces all references to the new operator with calls to the factory method.
Rules of thumb
  • Prototype co-opts one instance of a class for use as a breeder of all future instances.
  • Prototypes are useful when object initialization is expensive, and you anticipate few variations on the initialization parameters. In this context, Prototype can avoid expensive “creation from scratch”, and support cheap cloning of a pre-initialized prototype.
  • Factory Method: creation through inheritance. Protoype: creation through delegation.
  • Often, designs start out using Factory Method (less complicated, more customizable, subclasses proliferate) and evolve toward Abstract Factory, Protoype, or Builder (more flexible, more complex) as the designer discovers where more flexibility is needed.
  • Prototype doesn’t require subclassing, but it does require an “initialize” operation. Factory Method requires subclassing, but doesn’t require Initialize.
  • Designs that make heavy use of the Composite and Decorator patterns often can benefit from Prototype as well.

What is Singleton design pattern ?

Checkout the working code from my git hub repository using below link. It contains all possible ways of implementation of singleton with multi-thread issue which creates multiple instance of singleton.

https://github.com/premaseem/designPatterns/tree/master/SingletonPattern/src/com/premaseem/singleton

Singleton is a part of Gang of Four design pattern and it is categorized under creational design patterns.


In Java the Singleton pattern will ensure that there is only one instance of a class is created in the Java Virtual Machine. It is used to provide global point of access to the object. This is useful when exactly one object is needed to coordinate actions across the system. The concept is sometimes generalized to systems that operate more efficiently when only one object exists, or that restrict the instantiation to a certain number of objects. In terms of practical use Singleton patterns are used in logging, caches, thread pools, configuration settings, device driver objects.
For example, if you have a license for only one connection for your database or your JDBC driver has trouble with multithreading, the Singleton makes sure that only one connection is made or that only one thread can access the connection at a time.

What is Abstract Factory Design Pattern ?

Download the working code from my git hub repository from this link https://github.com/premaseem/designPatterns/tree/master/AbstractFactoryPattern

Basic Definition of Abstract Factory :

Abstract Factory patterns works around a super-factory which creates other factories. This factory is also called as Factory of factories. This type of design pattern comes under creational pattern as this pattern provides one of the best ways to create an object.

In Abstract Factory pattern an interface is responsible for creating a factory of related objects, without explicitly specifying their classes.

 

AbstractFactory1

 

The abstract factory pattern provides a way to encapsulate a group of individual factories that have a common theme without specifying their concrete classes.[1] In normal usage, the client software creates a concrete implementation of the abstract factory and then uses the generic interface of the factory to create the concrete objects that are part of the theme. The client doesn’t know (or care) which concrete objects it gets from each of these internal factories, since it uses only the generic interfaces of their products.[1] This pattern separates the details of implementation of a set of objects from their general usage and relies on object composition, as object creation is implemented in methods exposed in the factory interface.[2]

An example of this would be an abstract factory class DocumentCreator that provides interfaces to create a number of products (e.g. createLetter() and createResume()). The system would have any number of derived concrete versions of the DocumentCreator class like FancyDocumentCreator or ModernDocumentCreator, each with a different implementation of createLetter() and createResume() that would create a corresponding object like FancyLetter or ModernResume. Each of these products is derived from a simple abstract class like Letter or Resume of which the client is aware. The client code would get an appropriate instance of the DocumentCreator and call its factory methods. Each of the resulting objects would be created from the same DocumentCreator implementation and would share a common theme (they would all be fancy or modern objects). The client would only need to know how to handle the abstract Letter or Resume class, not the specific version that it got from the concrete factory.

A factory is the location of a concrete class in the code at which objects are constructed. The intent in employing the pattern is to insulate the creation of objects from their usage and to create families of related objects without having to depend on their concrete classes.[2] This allows for new derived types to be introduced with no change to the code that uses the base class.

Use of this pattern makes it possible to interchange concrete implementations without changing the code that uses them, even at runtime. However, employment of this pattern, as with similar design patterns, may result in unnecessary complexity and extra work in the initial writing of code. Additionally, higher levels of separation and abstraction can result in systems which are more difficult to debug and maintain. Therefore, as in all software designs, the trade-offs must be carefully evaluated.

what’s the difference between a simple factory, a factory method design pattern, and an abstract factory?

Thing that all three have in common is that they are responsible for creating objects.  The calling class (which we call the “client”) wants an object, but wants the factory to create it. I guess if you wanted to sound really professional, you could say that factories are used to encapsulate instantiation.

So what’s the difference between a simple factory, a factory method design pattern, and an abstract factory?

– A Simple factory is normally called by the client via a static method, and returns one of several objects that all inherit/implement the same parent.
– The Factory Method design is really all about a “create” method that is implemented by sub classes.
– Abstract Factory design is about returning a family of related objects to the client.  It normally uses the Factory Method to create the objects.

You can checkout the working project from my git hub repository, here is the link : https://github.com/premaseem/designPatterns/commit/94cdd85ac5f7080fb1be03dc885d6a6dc3b1ad8c#diff-d41d8cd98f00b204e9800998ecf8427e

Let us take a detailed look in each of them with minute details.

Simple Factory
The easiest way for me to remember this is that a simple factory is called directly by the class which wants to create an object (the calling class is referred to as the “client”).  The simple factory returns one of many different classes.  All the classes that a simple factory can return either inherit from the same parent class, or implement the same interface.

simpleFactory

Step One: you call a method in the factory.  Here it makes sense to use a static method.  The parameters for your call tell the factory which class to create.
Step Two:  the factory creates your object. The only thing to note is that of all the objects it can create, the objects have the same parent class, or implement the same interface.
Step Three: factory returns the object, and this is why step two makes sense.  Since the client didn’t know what was going to be returned, the client is expecting a type that matches the parent class /interface.

Please note that this is not an “official” design pattern.

 

Factory Method
The official definition of the pattern is something like: a class which defers instantiation of an object to subclasses.  An important thing to note right away is that when we’re discussing the factory pattern, we’re not concentrating on the implementation of the factory in the client, but instead we’re examining the manner in which objects are being created.
In this example the client doesn’t have a direct reference to the classes that are creating the object, but instead has reference to the abstract “Creator”. (Just because the creator is abstract, doesn’t mean this is the Abstract Factory!).  It is a Factory Method because the children of “Creator” are responsible for implementing the “Create” method. Another key point is that the creator is returning only one object.   The object could be one of several types, but the types all inherit from the same parent class.

factoryMethod

Step One: the client maintains a reference to the abstract Creator, but instantiates it with one of the subclasses.  (i.e. Creator c = new ConcreteCreator1(); )
Step Two: the Creator has an abstract method for creation of an object, which we’ll call “Create”.  It’s an abstract method which all child classes must implement.  This abstract method also stipulates that the type that will be returned is the Parent Class or the Interface of the “product”.
Step Three: the concrete creator creates the concrete object.  In the case of Step One, this would be “Child Class A”.
Step Four: the concrete object is returned to the client.  Note that the client doesn’t really know what the type of the object is, just that it is a child of the parent.

 

Abstract Factory
This is biggest pattern of the three.  I also find that it is difficult to distinguish this pattern from the Factory Method at a casual glance.  For instance, in the Factory Method, didn’t we use an abstract Creator?  Wouldn’t that mean that the Factory Method I showed was a actually an Abstract Factory?  The big difference is that by its own definition, an Abstract Factory is used to create a family of related products (Factory Method creates one product).

AbstractFactory

Step One:  the client maintains a reference to an abstract Factory class, which all Factories must implement.  The abstract Factory is instantiated with a concrete factory.
Step Two: the factory is capable of producing multiple types.  This is where the “family of related products” comes into play.  The objects which can be created still have a parent class or interface that the client knows about, but the key point is there is more than one type of parent.
Step Three: the concrete factory creates the concrete objects.
Step Four: the concrete objects are returned to the client.  Again, the client doesn’t really know what the type of the objects are, just that are a children of the parents.
See those concrete factories?  Notice something vaguely familiar?  There using the Factory Method to create objects.