Thursday, May 3, 2012

Structural Patterns - 4.Decorator Pattern

If we want to add new behaviors to our object during runtime, we can choose Decorator Pattern. In this pattern, we define a class and some set of behaviors applicable to the class separately.

We can patch up the behaviors to the class dynamically with out altering the class implementation.

In other words, the object can be decorated dynamically with various behaviors as per the need. Here,both the decorator and the object to be decorated belong, to the same abstract type.

Consider an example of creating a rainbow. By default, rainbow is having a single color as its behavior. We can add or remove colors to/from the rainbow dynamically.Hence, the rainbow object can be constructed and the colors can be added/removed on the fly.

Rainbow is an implementation of the abstract type Colors. We implement separate decorators for each and every color so that both rainbow and all other decorators belong to the same type, Colors.

Following class diagram will explain the concept in detail,

Here, we can add any new decorator or repeat the existing decorator without altering the Rainbow code.

Based on the above diagram the following code snippet shows the decorator pattern in action,

  Colors rainbow = new Rainbow();
  rainbow = new IndigoDecorator(rainbow); //Decorator 1 (Indigo)
  rainbow = new VioletDecorator(rainbow); // Decorator 2 (Indigo)


Similarly, we can add dynamic behaviors to the rainbow object as,  

  rainbow=new AnyColorDecorator(rainbow);  //Decorator N (Any Color)

we can also, decorate the rainbow class with the same color, repeated for any number of times.


In the Java API, InputStreams, Readers,etc are having decorator implementations.

Thursday, April 26, 2012

Structural Patterns - 3.Composite Pattern

The Composite Pattern is a very simple pattern to represent a complex structure of data. Whenever in an application, if we need to design a tree structure with leaf and nodes then this pattern could be a right candidate.

This pattern treats both the nodes and the leaves in the same way as they are the parts of the same tree.A parent-child hierarchy of many levels is a complex task to handle through the code. A child can have many children so that it will become a parent by itself.

Some children may not become a parent as they may not have any children on their own. This type of relationship can be gone to the depth of any level (ex:-parent/child generations together).

Having a design to maintain or accomodate such complex structure is a hard task. Thanks to Composite pattern which makes our life easy in the above scenario.Let us consider the below class diagram explaining the Composite Pattern,


Here, we have a generic Human Interface having two implementations
a) Child
b) Parent


The child class would be a leaf node which won't have any furthur nodes attached to it whereas a parent class is composed of a list of nodes of type Human.

Again those nodes may be either parent or child. This pattern appears recursively so that we can handle theparent and child objects to any number of generations.

Find below the structure of sample data which operates over the composite pattern,



Following code snippet will explain the above mentioned structure,
 public static void main(String[] args) {
 
  Parent one=new Parent("Gen1Parent");
  Human two=new Child("Gen2Child");
  Parent three=new Parent("Gen2Parent");
  Parent four=new Parent("Gen3Parent");
  Human five=new Child("Gen3Child");
  three.add(five);
  three.add(four);
  one.add(three);
  one.add(two);


  printItems(one); //Method to print all the values from the Tree
 
 }
 

Following code snippet will show how to iterate over the list of values in order to fetch the nodes and their leaves,

 public static void printItems(Parent parent){
         System.out.println(parent.getName());
  for(Human human:parent.getChildren()){
   if(human.getType().equals("Parent")){
   
    printItems((Parent)human);
   }else{
    System.out.println(human.getName());
   }
  }
 }

Tuesday, April 24, 2012

Structural Patterns - 2.Bridge Pattern

There are scenarios where we may need to deal with different combinations of abstractions and their implementations.

Bridge pattern helps us to seperate/decouple the abstraction and its implementation. We can use composition in order to associate an abstraction to a particular implementation. This will help us to design an extensible application.

Here, the abstractions and implementations where nowhere related to each other.

For example, We are having some abstractions of Pen like fountain pen, ball point pen,etc. As an implementation we can have some documents or contents like poem,essay,etc can be written out of a Pen.

Here, we compose Content to the Pen class so that we can use any type of pen to draft any type of content. The following class diagram explains this pattern,







Code to associate an abstraction to an implementation dynamically,


  Pen[] pens=new Pen[]{new BallPointPen(new Essay()),
                                                                 new FountainPen(new Poem())};
  for(Pen pen:pens){  
         System.out.println(pen.write());
  }

In the above code snippet, we dynamically associate the Essay and Poem instances to BallPointPen and FountainPen instances respectively.


In the BallPointPen/FountainPen class, we can handle this association as follows,


            public BallPointPen(Content content) {  
                      this.content=content;
            }
           @Override
           public String write() {  
                      return content.createContent()+" with BallPoint Pen";
           }

Thursday, April 19, 2012

Structural Patterns - 1.Adapter Pattern

So far, we discussed about the ways of creating an object and patterns involved during object creation.

Next we are going to see about the Structural patterns. They mostly deal with the way the classes or interfaces or represented or related. The influence of class structures on achieving a functionality will be widely discussed with a set of patterns.

Adapter Pattern

This is one among the most frequently used Design Patterns. The main benefit in going for the Adapter pattern, is to establish proper communication between two or more incompatible interfaces. In otherwords, adapter makes two different interfaces communicate each other.

There are two types of Adapters,
a) Class Adapters and
b) Object Adapters

Class Adapters

Consider, there are two different interfaces requires communication between each other. The Adapter class will inherit both the interfaces and overrides the implementation by custom code. Message from one interface will be taken and customized in such a way the other interface could process it.

A simple example of Class Adapters can be seen below,



In the above design, we want to transfer some data from a USB device to an HDMI device. So, we defined an Adapter class USBHDMIAdapter by inheriting both USBSource and HDMISource.

While writing the implementation for the method getHDMIData(), we internally fetch the USBData and perform customizations in order to make the data compatible with HDMI. Finally return the data back to the HDMI Source.

Sample code snippet for better understanding,

In the Adapter class we write our implementation for the getHDMIData() as follows,
public String getHDMIData() {
String hdmiData=getData().replace("USB", "HDMI");
return hdmiData;
}


and in the Client class we can invoke the Adapter as stated below,

USBSource usbSource=new USBSource();
usbSource.setData("USB Movie - 123");

HDMISource hdmiSource=new USBHDMIAdapter(usbSource);
System.out.println(hdmiSource.getHDMIData());


Object Adapters

They are very much similar to the Class Adapters but instead of generalization we use composition. We compose the USBSource object and write implementation for the HDMISource with our custom code.

Following design explains the Object Adapter pattern,



The source code for defining the Object Adapter may look as specified below,

class USBHDMIAdapter implements HDMISource{

private USBSource usbSource;

public USBHDMIAdapter(USBSource source) {
this.usbSource=source;
}

@Override
public String getHDMIData() {
String hdmiData=usbSource.getData().replace("USB", "HDMI");
return hdmiData;
}

}

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();