What we get as a result of this:

“Concrete implementations is decoupled from dynamic behaviours and responsibilities.”

UML Class Diagram :

Code Snippets

Step 1

Create an interface Shape.java


public interface Shape {
  void draw();
}

Step 2

Create a class  and  implementing  interface.

public class Square implements Shape {
   @Override
   public void draw() {
     System.out.println("Draw a Square Shape");
   }
}
public class Circle implements Shape {
   @Override
   public void draw() {
      System.out.println("Draw a Circle Shape ");
   }
}

Step 3

Create abstract Decorator class  implementing the  interface.

public abstract class ShapeDecorator implements Shape {
   protected Shape shapeToBeDecorated;
   public ShapeDecorator(Shape shapeToBeDecorated){
          this. shapeToBeDecorated = shapeToBeDecorated;
   }
   ...
   ...  
    public void draw(){
     shapeToBeDecorated.draw();
  }
}

Step 4

Create a class  concrete decorator class extending the  class.

public class BlueShapeDecorator extends ShapeDecorator {
  //Pass the object to be decorated to the constructor
  public BlueShapeDecorator(Shape shapeToBeDecorated) {
     super(shapeToBeDecorated);
  }
  ...
  ...
  @Override
  public void draw() {
    ShapeToBeDecorated.draw();
    setBlueBorderLine(shapeToBeDecorated);
  }
  //
  private void setBlueBorderLine(Shape shapeToBeDecorated){
     System.out.println("Add border Line to Blue Shape");
  }
}

Step 5

Use the Blue to decorate  objects in 

public class DecoratorPatternSample {
    public static void main(String[] args) {
      Shape circle = new Circle();
      Shape blueCircle = new BlueShapeDecorator(new Circle());
      Shape blueSquare = new BlueShapeDecorator(new Square());  
      ...         
      ...
      System.out.println("Circle without border");
      circle.draw();
      ...
      System.out.println("Circle decorated with  Blue border");
      blueCircle.draw();
      ...
      ...
      System.out.println (“Square decorated with  Blue border ");
      blueSquare.draw() 
   }
}



Thanks for reading this article. You may find the article on my Medium blog as well.

Similar Articles

Leave a Reply