Sunday, 5 January 2014

Decorator Design pattern - Implementation [Shape]



Click here to watch in Youtube : https://www.youtube.com/watch?v=b-6OtMYNkpw

Click the below Image to Enlarge
Decorator Design pattern - Implementation [Shape]


Decorator Design pattern - Implementation [Shape] - Class Diagram






























Shape.java

public interface Shape
{
void draw();
}

Circle.java

public class Circle implements Shape
{

@Override
public void draw()
{
System.out.println("Shape: Circle has been drawn");
}
}

Rectangle.java

public class Rectangle implements Shape
{

@Override
public void draw()
{
System.out.println("Shape: Rectangle has been drawn");
}
}

ShapeDecorator.java

public abstract class ShapeDecorator implements Shape
{
protected Shape decoratedShape;

public ShapeDecorator( Shape decoratedShape )
{
this.decoratedShape = decoratedShape;
}

public void draw()
{
decoratedShape.draw();
}
}

BlueShapeDecorator.java

public class BlueShapeDecorator extends ShapeDecorator
{

public BlueShapeDecorator( Shape decoratedShape )
{
super(decoratedShape);
}

@Override
public void draw()
{
decoratedShape.draw();
setColor(decoratedShape);
}

private void setColor( Shape decoratedShape )
{
System.out.println("Color: Blue has been applied to "+decoratedShape);
}
}

DecoratorPatternDemo.java

public class DecoratorPatternDemo
{
public static void main(String[] args)
{

Shape blueCircle = new BlueShapeDecorator(new Circle());

Shape blueRectangle = new BlueShapeDecorator(new Rectangle());

System.out.println("\nCreate Blue color Circle using BlueShapeDecorator");
blueCircle.draw();

System.out.println("\nCreate Blue color Rectangle using BlueShapeDecorator");
blueRectangle.draw();
}
}

Ouput

Create Blue color Circle using BlueShapeDecorator
Shape: Circle has been drawn
Color: Blue has been applied to Circle@30c221

Create Blue color Rectangle using BlueShapeDecorator
Shape: Rectangle has been drawn
Color: Blue has been applied to Rectangle@119298d


See also:

  • Decorator Design pattern - Introduction
  • Decorator Design pattern - Real Time Example [Dosa]
  • Decorator Design pattern - Real Time Example [Ice Cream]
  • Decorator Design pattern - Real Time Example [Pizza]
  • Decorator Design pattern - Real Time Example [Car]
  • Decorator Design pattern - Class Diagram
  • Decorator Design pattern - Sequence Diagram
  • Decorator Design pattern - Implementation [Dosa]
  • Decorator Design pattern - Implementation [Pizza]
  • Decorator Design pattern - Implementation [Ice Cream]
  • Decorator Design pattern - Implementation [Car]
  • Decorator Design pattern - Key Points
  • All Design Patterns Links
  • No comments:

    Post a Comment

    Google+ Followers

    Google+ Badge