Thursday, March 22, 2012

Creational Patterns - 5.Singleton Pattern

It's a costlier effort to create an object for the class as many times we need. There is a better way to handle such situations. We need to consider re-using the object once its got created.
Let us create an object and re-use it throughout the application wherever needed. Therefore, not more than a single instance of the class exists. This is called as a Singleton pattern.

In general, we create a self composed class with a closed constructor. So that, the instantiation can be customized with the help of a factory method.

Following class diagram shows a singleton class,




In the book class we made the constructor private and defined a static method getInstance().The object creation activity is delegated to the custom getInstance() method and the constructor is closed. As a result, we validate the object whether it already exists or not.
The getInstance() method will not create an instance if one already exists.

class Book{
private static Book book;
private Book() {
}
public static Book getInstance(){
if(null==book)
book=new Book(); // Lazy Initialization
return book;
}
}


The above sample is based on Lazy Initialization pattern.

One simpler way to create the same singleton class without Lazy Initialization is given below,



class Book{
private static final Book book=new Book();
private Book() {
}
public static Book getInstance(){
return book;
}
}



We have one more approach to achieve a perfect singleton with the help of enum types.
Since the data members of the enum types are always constants,the method calls will be happening over a singleton object.

Following design will explain the concept clearly.





Here, Book is a enum type having a constant INSTANCE which can act as a singleton.
Using the singleton object INSTANCE, we can invoke the method getPrice() from the enum Book.

Wednesday, March 14, 2012

Creational Patterns - 4.Prototype Pattern

Generally, object creation is a costlier task in an application development. Whenever creating an object, we need to be more keen on the way how it is being constructed. To optimize the object creation we may consider the creational patterns wherever applicable to our business need.

Consider a scenario, where we need to construct a set of objects belong to a similar kind but with small differences among them.

It would be a costlier operation to create all the individual objects using "new" for the above scenario.

For example,
We are creating a generic LayoutTemplate.Parts of a LayoutTemplate would consists of header,body and footer.
UI providers of various discipline can construct their own layouts using the generic layout template.
Think about a scenario where we need to construct a bunch of layouts like Web Layout, Desktop Layout, Android Layout,etc.,

Instead of creating seperate instances for each and every layout, we create a single layout object(Prototype) and customize it to generate other layouts. This will reduce the overhead of object creation for every layout type.

In order to achieve this, we have to make use of clone() method to our layout class. Clonning will be supported only over a cloneable object. For that, we need to implement the Cloneable interface and override the clone() method.

Note: clone() method should throw CloneNoteSupportedException.

Following class diagram will explain the prototype design pattern.




We can create a Generic Layout object as,

LayoutTemplate genericLayout=new ConcreteLayout("Text header", "Text Footer", "Text body");

This is the Prototype object for our layout creation. Using this,we can create other layouts as specified below.

LayoutTemplate webLayout=(LayoutTemplate)genericLayout.clone();
webLayout.setFooter("HTML Footer");
//Customize the clonned object as per the need

LayoutTemplate desktopLayout=(LayoutTemplate)genericLayout.clone();
desktopLayout.setHeader("JMenubar");
//Customize the clonned object as per the need

Monday, March 5, 2012

Creational Patterns - 3.Builder Pattern

When dealing with the construction of complex objects,there always should be a consideration of builder pattern. This pattern abstracts the construction steps for an object. Different builders can implement the steps on their own way.

There is one more component called Director takes care of driving the builder for constructing an object.

Example Use Case:-

This use case involves the process of constructing a house.

Construction steps for a house may contain the following things,


  • Flooring
  • Wall construction
  • Roofing
We are going to construct,

  1. CountryTiledHouse
  2. TerraceHouse
Both the above mentioned houses are having their own styles for flooring,wall,roof,etc.

Here, we are going to abstract the construction process of the floor,wall and roof.

So that, different types of houses can construct them as per their taste.

Following class diagram will clearly explain the design approach,




The flow of constructing a CountryTiledhouse can be specified as follows,
1) Initialize our builder,

HouseBuilder houseBuilder=new TileHouseBuilder();

2) Ask the director to use the builder,

BuildingDirector director=new BuildingDirector(houseBuilder);


3) Ask the director to build the house

director.buildHouse();

4) Request the house from the builder after being built based on the director's instructions

System.out.println(houseBuilder.getHouse().getFloor());

If we need a TerraceHouse, we just need to change the builder as follows,

HouseBuilder houseBuilder=new TerraceBuilder();