Java Design Patterns Decorator Patterns

Introduction

Decorator Patterns attach responsibilities to an object dynamically.

Decorator Patterns provide a flexible way for extending functionality.

Decorator Patterns are open for extension but closed for modification.

Decorator Patterns add specific functionalities to specific object instead of to the whole class.

Use case

  • Adding border to a button.
  • Adding alert message for input field.

Example

abstract class Component {
   public abstract void doJob();
}

class ConcreteComponent extends Component {
   @Override/*ww  w  .  java  2s  .  c  om*/
   public void doJob() {
      System.out.println("Concrete Component");
   }
}

abstract class AbstractDecorator extends Component {
   protected Component com;

   public void setComponent(Component c) {
      com = c;
   }

   public void doJob() {
      if (com != null) {
         com.doJob();
      }
   }
}

class Decorator1 extends AbstractDecorator {
   public void doJob() {
      super.doJob();
      System.out.println("Adding additional thing from one decorator");
   }
}

class Decorator2 extends AbstractDecorator {
   public void doJob() {
      super.doJob();
      System.out.println("Adding additional thing from another decorator");
   }
}

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

      ConcreteComponent cc = new ConcreteComponent();

      Decorator1 decorator1 = new Decorator1();
      decorator1.setComponent(cc);
      decorator1.doJob();

      Decorator2 decorator2 = new Decorator2();
      decorator2.setComponent(decorator1);// Adding results from decorator1
      decorator2.doJob();
   }
}



PreviousNext

Related