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.
- Component Interface: Defines the interface for objects that can have responsibilities added to them dynamically.
- Concrete Component: The basic implementation of the Component interface.
- Decorator: Abstract class that implements the Component interface and has a reference to a Component object. It delegates all operations to this component.
- Concrete Decorators: Extend the Decorator class and add additional responsibilities to the component.
Let’s say we have a simple interface
Coffee which represents a coffee beverage:
We have a concrete implementation of
Now, let’s create a decorator
We can now create concrete decorators such as
Now let’s see how we can use these decorators:
Cost: 1.0, Description: Simple Coffee
Cost: 1.5, Description: Simple Coffee, Milk
Cost: 1.7, Description: Simple Coffee, Milk, Sugar
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.