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);
}
}
{
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();
}
}
{
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
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
No comments:
Post a Comment