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

No comments:

Post a Comment