Thursday, April 12, 2012

Decorator Design Pattern in Java


In this pattern(Decorator Design pattern), a decorator object is wrapped around the original object. This is typically achieved having the original object as a member of the decorator, the decorator object also provides a way to implement the new functionality. The decorator must conform to the interface of the original object (the object being decorated).

The definition of Decorator Design pattern is :

Attach additional responsibilities to an object dynamically. Decorators
provide a flexible alternative to subclassing for extending functionality.

Where to implement-

For example I have an Interface and its implementation class, and if i want to provide an extra functionality with out effecting the original interface and implementation class.

Also we should able to withdraw the extra functionality or responsibility that we are providing dynamically.

For Example: The java.util.Collections.unmodifiableCollection(Collection) removies the ability to change a given collection by wrapping it with a decorator that throws an UnSupportedException when you try to modify the Collection.

example..

Have an interface IComponent, with one method getDetails();
Also I have an implementation class Component for IComponent

If I have to provide extra functionality with out effecting the above 2 I can do the following..

Extend the IComponent With IDecorator interface which has the extra method declared doSomething()

that is

public interface IDecorator extends IComponent {
public void doSomething();
}

and provide the implementation to the IDecorator which has two methods getDetails, doSomething.

public class Decorator implements IDecorator {

IComponent component;

public Decorator(IComponent component) {
super();
this.component = component;
}

public void doSomething() {
System.out.println("Decorator does some stuff too");

}

public void getDetails() {
component.getDetails();
doSomething();

}

}


Here, with the same getDetails() of IComponent, we are achieving the extra functionality.


Here is the client class


public class Client {
public static void main(String[] args) {
IComponent comp = new Component();
IDecorator decorator = new Decorator(comp);
decorator.doStuff();
}

}

Stumble
Delicious
Technorati
Twitter

0 Comments:

Post a Comment