Categories
Algorithms & Design Design Pattern

Decorator Pattern

Square.java

public class Square {

	public Square() {
		// TODO Auto-generated constructor stub
	}
	
	public void draw(){
		System.out.println("Drawing the square..");
	}

}

ColorDecorator.java

public abstract class ColorDecorator {

	protected Square square;
	public ColorDecorator(Square square) {
		// TODO Auto-generated constructor stub
		this.square=square;
	}

	public abstract void applyColor();
	public void draw(){
		this.square.draw();
		this.applyColor();
	}
}

RedColorDecorator.java

public class RedColorDecorator extends ColorDecorator {

	public RedColorDecorator(Square square) {
		// TODO Auto-generated constructor stub
		super(square);
	}

	@Override
	public void applyColor() {
		// TODO Auto-generated method stub
		System.out.println("applying Red color");
	}
}

GreenColorDecorator.java

public class GreenColorDecorator extends ColorDecorator {

	public GreenColorDecorator(Square square) {
		// TODO Auto-generated constructor stub
		super(square);
	}

	@Override
	public void applyColor() {
		// TODO Auto-generated method stub
		System.out.println("applying green Color");
	}

}

DecoratorPatternDemo.java

public class DecoratorPatternDemo {

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

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//Create Square
		Square square = new Square();
		
		//Decorate Square with red color
		ColorDecorator redSquare = new RedColorDecorator(square);
		redSquare.draw();
		
		//Decorate Square with green color
		ColorDecorator greenSquare = new GreenColorDecorator(square);
		greenSquare.draw();
				

	}

}

Output

Leave a comment

Design a site like this with WordPress.com
Get started