What is Decorator Pattern?
Decorator pattern is a structural design pattern that attaches additional behaviors to an object dynamically. Decorators provide a flexible extension reason by composition rather than subclassing (inheritance).
When to use it?
Use Decorator pattern when you have many possible combination to construct an object.
Problem
Imagine we're developing a system for an ice cream shop. The shop has various ice creams and toppings. The system needs to display an ice cream description (including its toppings) and cost.
Our first version system is this:
This seems fine, but what if we could add toppings?
Our second version:
The problem is unveiled! Notice even they are not enough since we need ChocolateIceCreamWithChocolateChipsAndMapleNuts
and so on.
Solution
Decorator Pattern is also known as Wrapper Pattern since it works by wrapping additional functionality around an object. Wrapped object (ice cream) is called Component, and Wrapper object (topping) is called Decorator.
IceCream class
Components and decorators have common interfaceIceCream
class (you will see why later), they both declare asIceCream
object.Concrete IceCream classes
Each concrete ice cream overrides cost method since prices are different for each.Topping class
Topping class provides interface for concrete toppings and holds reference to anIceCream
object.Concrete Topping classes
If system needs another topping, say caramel source, what you need to do is just creatingCaramelSource
class which extendsTopping
class.
Structure
Decorator class uses composition and inheritance, it's crucial to understand their intent.
In Decorator pattern, we use the same type for both components & decorators. Decorator composites Component object to get behavior, that is, obtaining fields or methods defined in Component object. While Decorator inherits (extends) Component so that Decorator object can be declared as Component object.
Decorator pattern achieves open-closed principle, namely, open for extension and closed for modification. It's easy to add components or decorators. for instance, if you want to add another concrete decorator, you just need to create a class representing it and extends Decorator class.
Implementation in Java
// Component class
public abstract class IceCream {
public String description = "Unknown ice cream";
public String getDescription() {
return description;
}
public abstract double cost();
}
// Concrete component class
public class ChocolateIceCream extends IceCream {
public ChocolateIceCream() {
description = "ChocolateIceCream";
}
@Override
public double cost() {
return 1.99;
}
}
// Base decorator class
public abstract class Topping extends IceCream {
public IceCream iceCream;
// All subclasses (concrete decorator classes) need to implement getDescription method,
// by declaring this method as abstract, we enforce all subclasses to implement this method
public abstract String getDescription();
}
// Concrete decorator class
public class MapleNuts extends Topping {
public MapleNuts(IceCream iceCream) {
this.iceCream = iceCream;
}
@Override
public String getDescription() {
return iceCream.getDescription() + ", MapleNuts";
}
@Override
public double cost() {
return iceCream.cost() + .30;
}
}
// Concrete decorator class
public class PeanutButterShell extends Topping {
public PeanutButterShell(IceCream iceCream) {
this.iceCream = iceCream;
}
@Override
public String getDescription() {
return iceCream.getDescription() + ", PeanutButterShell";
}
@Override
public double cost() {
return iceCream.cost() + .30;
}
}
public class Client {
public static void main(String[] args) {
IceCream iceCream = new ChocolateIceCream();
System.out.println(iceCream.getDescription() + ", $" + iceCream.cost());
iceCream = new MapleNuts(iceCream);
System.out.println(iceCream.getDescription() + ", $" + iceCream.cost());
iceCream = new PeanutButterShell(iceCream);
System.out.println(iceCream.getDescription() + ", $" + iceCream.cost());
}
}
Output:
ChocolateIceCream, $1.99
ChocolateIceCream, MapleNuts, $2.29
ChocolateIceCream, MapleNuts, PeanutButterShell, $2.59
Pitfalls
- Often ends up in large number of classes being added to the system, where each class provides small behavior.
- You needs additional work if you want to let each decorator to know inner decorators. In above example, if you want to print
ChocolateIceCream, MapleNuts * 2
instead ofChocolateIceCream, MapleNuts, MapleNuts
, each decorators needs to know which toppings have been added so far (can be done by ArrayList for example).
You can check all the design pattern implementations here.
GitHub Repository
P.S.
I'm new to write tech blog, if you have advice to improve my writing, or have any confusing point, please leave a comment!
Thank you for reading :)
Top comments (6)
The explanation of the Decorator Pattern is quite insightful.
What are some practical scenarios where you found using the Decorator Pattern especially beneficial? Are there any common pitfalls developers should watch out for when implementing this pattern?
Thank you for your review!
I edited this blog and tried to introduce concrete example in "Problem" section.
I also mentioned about pitfalls as well.
The classic example of a real world use is the various reader classes in Java's
java.io
package. You've given a good toy example and explanation of the pattern, good work ππΌYh this could do with a lot of work, your first paragraph is a word salad and barely comprehensible
Thank you for your review!
I'll edit and try to improve this article.
Yeah, I read it like three times and just moved on hoping the article would explain it. But kind of just abruptly ended. ChatGPT?
Some comments may only be visible to logged-in visitors. Sign in to view all comments.