DEV Community

eidher
eidher

Posted on • Edited on

1

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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay