Tuesday, November 07, 2006

Decorator Design Pattern

Benefits of Decorator Design Pattern:

1. Make a responsibility easily added and removed dynamically.
2. More flexibility than static inheritance.
3. Provide an alternative to sub classing.
4. Add new function to an object without affecting other objects.
5. Transparent to the object.

What is Decorator Pattern :

Attach additional responsibilities or functions to an object dynamically or statically. Also known as Wrapper. Suppose we have some 10 objects and 2 of them need a special behavior, we can do this with the help of a decorator. The decorator pattern can be use wherever there is a need to add some functionality to the object or group of objects.
Java Design Patterns suggest that Decorators should be abstract classes and the concrete implementation should be derived from them.

Example of Decorator Pattern:

Christmas tree branches need to be decorated with the different types of branches.

package test.structural.decorator;

public abstract class Decorator {

// This method is used to decorate the branch of the Christmas tree
public abstract void place(Branch branch);

} // End of class

Above class has method place which places different types of items on the branches of the tree.

package test.structural.decorator;

public class ChristmasTree {

private Branch branch;

//returns the branch
public Branch getBranch() {
return branch;

}

} // End of class

You decorate the branches in three different ways; one is by putting different color balls on them, by putting different color squares on them and also by putting stars on them.


Implementation of one of the above three decorator will as below

package test.structural.decorator;

// Decorates the branch of the tree with different color balls.

public class BallDecorator extends Decorator {

public BallDecorator(ChristmasTree tree) {
Branch branch = tree.getBranch();place(branch);
}
//The method places each decorative item on the tree.
public void place(Branch branch) {
branch.put("ball");
}

}// End of class

Same way you can write the SquareDecorator and StarDecorator.

Instantiation of the BallDecorator will be like

BallDecorator decorator = new BallDecorator(new ChristmasTree());

Ball decorator will be instantiated and a branch of the Christmas tree will be decorated with different color balls.

This pattern provides functionality to objects in a more flexible way rather than inheriting from them. Disadvantage of the decorator pattern will be maintenance of the code as lots of similar looking small object for each decorator.

1 comment:

PF withdrawal Process said...

Add some other tips also