You are currently viewing Guide to Decorator Pattern in Java with Examples

Guide to Decorator Pattern in Java with Examples

In Java, decorators are a structural design pattern that allows behavior to be added to individual objects dynamically, without affecting the behavior of other objects from the same class. Decorators are particularly useful when you need to add functionality to objects in a flexible and reusable way. This tutorial will explain the decorator pattern in Java with examples.

What is the Decorator Pattern?

The decorator pattern is a structural design pattern that allows behavior to be added to individual objects, either statically or dynamically, without affecting the behavior of other objects from the same class. It is useful for adding new functionality to objects without altering their structure.

Key Components:

  1. Component Interface: Defines the interface for objects that can have responsibilities added to them dynamically.
  2. Concrete Component: The basic implementation of the Component interface.
  3. Decorator: Abstract class that implements the Component interface and has a reference to a Component object. It delegates all operations to this component.
  4. Concrete Decorators: Extend the Decorator class and add additional responsibilities to the component.

Example:

Let’s say we have a simple interface Coffee which represents a coffee beverage:

We have a concrete implementation of Coffee called SimpleCoffee:

Now, let’s create a decorator CoffeeDecorator:

We can now create concrete decorators such as Milk and Sugar:

Usage:

Now let’s see how we can use these decorators:

Output:

Cost: 1.0, Description: Simple Coffee
Cost: 1.5, Description: Simple Coffee, Milk
Cost: 1.7, Description: Simple Coffee, Milk, Sugar

Conclusion:

The decorator pattern allows you to add behavior to objects dynamically. It promotes code reuse and follows the open/closed principle by allowing classes to be easily extended with new functionality without modifying existing code.

Leave a Reply