Tuesday, May 31, 2016

Decorator Pattern implementation in java tutorial or example

What is Decorator Patter?

It changes(extends or modify) the behavior of an instance at run time.

When to use Decorator Pattern:

We can choose any single object of a class and modify its behaviour leaving the other instances unmodified.Inheritance adds functionality to classes whereas the decorator pattern adds functionality to objects in other objects.

Implementation:

/**
 * @author Abhinaw.Tripathi
 *
 */
interface House
{
  public String makeHouse();
}

class SimpleHouse implements House
{

@Override
public String makeHouse() {
// TODO Auto-generated method stub
return "Base House";
}

}

abstract class HouseDecorator implements House
{
protected House house;

public HouseDecorator(House h)
{
this.house=h;
}
public String makeHouse()
{
return house.makeHouse();
}
}

class ColorDecorator extends HouseDecorator
{

public ColorDecorator(House h) {
super(h);
// TODO Auto-generated constructor stub
}

private String addColors()
{

return "+colors";
}
public String makeHouse()
{
return house.makeHouse() + addColors() ;
}

}

public class DecoratorPatternTest {

/**
*
*/
public DecoratorPatternTest() {
// TODO Auto-generated constructor stub
}

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

House house =new ColorDecorator(new ColorDecorator(new SimpleHouse())) ;
System.out.println(house.makeHouse());
}


}



No comments: