DEV Community

eidher
eidher

Posted on • Updated on

Decorator Pattern

Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.
Alt Text

Participants

  • Component: defines the interface for objects that can have responsibilities added to them dynamically.
  • ConcreteComponent: defines an object to which additional responsibilities can be attached.
  • Decorator: maintains a reference to a Component object and defines an interface that conforms to Component's interface.
  • ConcreteDecorator: adds responsibilities to the component.

Code

public class Main {

  public static void main(String[] args) {
    ConcreteComponent c = new ConcreteComponent();
    ConcreteDecoratorA d1 = new ConcreteDecoratorA();
    ConcreteDecoratorB d2 = new ConcreteDecoratorB();
    d1.setComponent(c);
    d2.setComponent(d1);
    d2.operation();
  }
}

public interface Component {
  void operation();
}

public class ConcreteComponent implements Component {

  @Override
  public void operation() {
    System.out.println("ConcreteComponent.operation()");
  }
}

public abstract class Decorator implements Component {

  protected Component component;

  public void setComponent(Component component) {
    this.component = component;
  }

  @Override
  public void operation() {
    if (component != null) {
      component.operation();
    }
  }
}

public class ConcreteDecoratorA extends Decorator {

  private static final String ADDED_STATE = "ConcreteDecoratorA.operation()";

  @Override
  public void operation() {
    super.operation();
    System.out.println(ADDED_STATE);
  }

}

public class ConcreteDecoratorB extends Decorator {

  @Override
  public void operation() {
    super.operation();
    addedBehavior();
    System.out.println("ConcreteDecoratorB.operation()");
  }

  private void addedBehavior() {
    System.out.println("ConcreteDecoratorB.addedBehavior()");
  }
}
Enter fullscreen mode Exit fullscreen mode

Output

ConcreteComponent.operation()
ConcreteDecoratorA.operation()
ConcreteDecoratorB.addedBehavior()
ConcreteDecoratorB.operation()
Enter fullscreen mode Exit fullscreen mode

Top comments (0)