Decorator Design Pattern in Java
The decorator design pattern in Java adds behaviour to an object by wrapping it in another object that has the same interface. Each wrapper does its own small job, such as adding a fee, compressing data or writing an audit log, and then passes the call to the object inside, so features can be stacked in any combination at runtime.
It matters because inheritance does not scale when features combine. Logging, masking and retries for both email and SMS would need a subclass for every mix. Decorators replace that tree of subclasses with small, reusable layers. Decorator is a structural design pattern, and you already use it every time you write new BufferedReader(new InputStreamReader(...)).
1. What Is the Decorator Design Pattern?
The GoF intent is: "Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality."
The idea rests on two facts about every decorator: it is a component (it implements the same interface), and it has a component (it holds a reference to the object it wraps). Because of the first fact, a decorated object can be used anywhere the plain one could. Because of the second, decorators can wrap other decorators, forming a chain.
When a method is called on the outermost layer, it does its extra work before and/or after forwarding the call inward, until the call reaches the original object. Adding a feature means writing one new decorator class, not touching existing ones, which is the Open/Closed Principle in action. Each decorator also has one reason to change, which keeps it aligned with the Single Responsibility Principle.
2. Key Components
| Component | Responsibility | In the Basic Example |
|---|---|---|
| Component | The interface shared by the real object and all decorators | Purchase |
| Concrete Component | The original object that does the core work | BaseOrder |
| Base Decorator | Holds the wrapped component and forwards every call by default | PurchaseDecorator |
| Concrete Decorators | Override selected methods to add behaviour | GiftWrap, ExpressDelivery, Insurance |
The client builds the chain once, holding only the outermost object as a Purchase. Each call travels inward through the layers to BaseOrder, and each layer adjusts the result on the way back out.
3. When Is Decorator Useful?
- Optional add-ons: an order with any mix of gift wrap, express delivery and insurance.
- Layered data processing: reading a file that is compressed, buffered and decoded, one concern per layer.
- Cross-cutting policies: fraud screening, idempotency and auditing around a payment gateway, switched on per environment.
4. UML Class Diagram
The diagram shows the Basic Example.
Purchase and also holds a Purchase, so decorators can wrap the base order or each other.Purchaseis the component interface.BaseOrderandPurchaseDecoratorboth implement it.PurchaseDecoratoralso holds onePurchase(hollow diamond, "wraps"). This is-a plus has-a combination is the heart of the pattern.- The concrete decorators extend the abstract decorator (solid line, hollow triangle) and override only what they change.
- Because the wrapped type is the interface, a decorator can wrap a
BaseOrderor another decorator.
5. Step-by-Step Execution Flow
Take new Insurance(new ExpressDelivery(new GiftWrap(new BaseOrder("2000.00")))):
- The objects are built from the inside out, so
Insuranceis the outermost layer. - The client calls
cost()onInsurance, which first asks its inner object,ExpressDelivery. ExpressDeliveryasksGiftWrap, which asksBaseOrder, which returns 2000.00.- On the way back out,
GiftWrapadds 49 (2049.00), andExpressDeliveryadds 99 (2148.00). Insuranceadds 2% of 2148.00 and returns 2190.96.
Wrap the same parts in a different order and the insurance is calculated on a different base, which is why decorator order matters.
6. Real-World Use Cases
- E-commerce: price add-ons, discounts and taxes applied as layers.
- Payments and banking: fraud screening, idempotency, auditing and metrics around a gateway client.
- Notifications: masking sensitive data, adding tracking links, or logging around any sender.
- The JDK:
java.iois built on decorators.BufferedInputStream,DataInputStreamandGZIPInputStreamextendFilterInputStreamand wrap anotherInputStream.Collections.unmodifiableList()andCollections.synchronizedList()wrap a list with the same interface and add behaviour. - Servlet and Spring:
HttpServletRequestWrapperis a decorator base class for requests, and Spring'sContentCachingRequestWrapperbuilds on it to cache the body for logging. In WebFlux,ServerHttpRequestDecoratorplays the same role.
7. Problem Without the Pattern
Adding features through inheritance:
public class NotifierWithoutDecorator {
static class EmailNotifier {
void send(String to, String message) { System.out.println(" email to " + to + ": " + message); }
}
static class SmsNotifier {
void send(String to, String message) { System.out.println(" sms to " + to + ": " + message); }
}
// Each feature combination needs its own subclass
static class LoggedEmailNotifier extends EmailNotifier {
@Override
void send(String to, String message) {
System.out.println(" [log] sending");
super.send(to, message);
}
}
static class MaskedLoggedEmailNotifier extends LoggedEmailNotifier {
@Override
void send(String to, String message) {
super.send(to, message.replaceAll("\\d{4}(?=\\d{4})", "****")); // mask card numbers
}
}
// Same features for SMS? Copy both classes again
static class LoggedSmsNotifier extends SmsNotifier {
@Override
void send(String to, String message) {
System.out.println(" [log] sending");
super.send(to, message);
}
}
public static void main(String[] args) {
new MaskedLoggedEmailNotifier().send("asha@example.com", "Card 41111111 charged");
new LoggedSmsNotifier().send("+91-98xxxxxx10", "Card 41111111 charged"); // no masking class for SMS yet
}
}
[log] sending
email to asha@example.com: Card ****1111 charged
[log] sending
sms to +91-98xxxxxx10: Card 41111111 charged
- Class explosion: two channels and two features already need four extra classes; each new feature doubles that.
- Duplication: the logging code appears once per channel.
- A real gap: SMS has no masking class yet, so the card number leaks.
- Fixed at compile time: you cannot switch features on or off per customer or environment.
8. Solution Using the Pattern
Give both channels one Notifier interface, then write Logging and Masking as decorators that implement it and wrap any other notifier. Any channel can now get any feature by wrapping: new Logging(new Masking(new SmsNotifier())).
The number of classes grows with the number of features, not with their combinations. Each feature is written once, the SMS leak disappears because masking works for every channel, and the chain can be assembled from configuration at runtime. The examples apply this structure to prices, I/O streams and payments.
9. Decorator Design Pattern in Java: Code Examples
Each example is a single file that runs on Java 21 with java FileName.java.
Basic Example: Order Add-ons
Problem: customers can add gift wrap, express delivery and insurance in any combination, and insurance is a percentage of whatever it covers.
import java.math.BigDecimal;
import java.math.RoundingMode;
public class PurchaseDecoratorDemo {
// Component
interface Purchase {
BigDecimal cost();
String description();
}
// Concrete component
static final class BaseOrder implements Purchase {
private final BigDecimal cartTotal;
BaseOrder(String cartTotal) { this.cartTotal = new BigDecimal(cartTotal); }
public BigDecimal cost() { return cartTotal; }
public String description() { return "Cart"; }
}
// Base decorator: holds a Purchase and delegates to it
abstract static class PurchaseDecorator implements Purchase {
protected final Purchase inner;
protected PurchaseDecorator(Purchase inner) { this.inner = inner; }
public BigDecimal cost() { return inner.cost(); }
public String description() { return inner.description(); }
}
// Concrete decorators
static final class GiftWrap extends PurchaseDecorator {
GiftWrap(Purchase inner) { super(inner); }
@Override public BigDecimal cost() { return inner.cost().add(new BigDecimal("49.00")); }
@Override public String description() { return inner.description() + " + gift wrap"; }
}
static final class ExpressDelivery extends PurchaseDecorator {
ExpressDelivery(Purchase inner) { super(inner); }
@Override public BigDecimal cost() { return inner.cost().add(new BigDecimal("99.00")); }
@Override public String description() { return inner.description() + " + express"; }
}
// Insurance costs 2% of whatever it wraps, so its position matters
static final class Insurance extends PurchaseDecorator {
Insurance(Purchase inner) { super(inner); }
@Override public BigDecimal cost() {
BigDecimal base = inner.cost();
return base.add(base.multiply(new BigDecimal("0.02")).setScale(2, RoundingMode.HALF_UP));
}
@Override public String description() { return inner.description() + " + insurance"; }
}
static void print(Purchase p) {
System.out.println(p.description() + " = Rs. " + p.cost());
}
public static void main(String[] args) {
print(new BaseOrder("2000.00"));
print(new GiftWrap(new BaseOrder("2000.00")));
print(new Insurance(new ExpressDelivery(new GiftWrap(new BaseOrder("2000.00")))));
print(new ExpressDelivery(new GiftWrap(new Insurance(new BaseOrder("2000.00"))))); // same parts, different order
}
}
Important classes and methods
PurchaseDecoratorforwards both methods by default, so each concrete decorator overrides only what it changes.innerisfinal, so a decorator always wraps the same object.Insurancecalculates its fee frominner.cost(), so its result depends on its position.
Expected output
Cart = Rs. 2000.00
Cart + gift wrap = Rs. 2049.00
Cart + gift wrap + express + insurance = Rs. 2190.96
Cart + insurance + gift wrap + express = Rs. 2188.00
How it runs
- The plain cart costs 2000.00; gift wrap adds 49.
- With insurance outermost, it covers wrap and delivery too: 2148.00 + 2% = 2190.96.
- With insurance innermost, it covers only the cart: 2040.00 + 49 + 99 = 2188.00.
Practical Example: Java I/O Streams and a Custom Decorator
Problem: write a compressed sales export, read it back line by line, and measure how many bytes pass through each layer, without changing any JDK class.
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
public class StreamDecoratorDemo {
// Our own decorator: counts bytes passing through any InputStream
static final class CountingInputStream extends FilterInputStream {
private long count;
CountingInputStream(InputStream in) { super(in); }
@Override
public int read() throws IOException {
int b = super.read();
if (b != -1) count++;
return b;
}
@Override
public int read(byte[] buffer, int off, int len) throws IOException {
int n = super.read(buffer, off, len);
if (n > 0) count += n;
return n;
}
long count() { return count; }
}
public static void main(String[] args) throws IOException {
// Write: PrintWriter -> OutputStreamWriter -> GZIPOutputStream -> ByteArrayOutputStream
ByteArrayOutputStream file = new ByteArrayOutputStream();
try (PrintWriter out = new PrintWriter(new OutputStreamWriter(new GZIPOutputStream(file), StandardCharsets.UTF_8))) {
for (int i = 1; i <= 200; i++) {
out.printf("2026-11-02,store-%03d,orders=%d\n", i % 5, 40 + i % 7); // 200 rows; \n keeps the size the same on every OS
}
}
// Read: each wrapper adds one job on top of the stream it wraps
CountingInputStream onDisk = new CountingInputStream(new ByteArrayInputStream(file.toByteArray()));
CountingInputStream unzipped = new CountingInputStream(new GZIPInputStream(onDisk));
int lines = 0;
String first = null;
try (BufferedReader reader = new BufferedReader(new InputStreamReader(unzipped, StandardCharsets.UTF_8))) {
String line;
while ((line = reader.readLine()) != null) {
if (first == null) first = line;
lines++;
}
}
System.out.println("First line: " + first);
System.out.println("Lines read: " + lines);
System.out.println("Bytes after unzip: " + unzipped.count());
System.out.println("Compressed bytes smaller than a tenth? " + (onDisk.count() * 10 < unzipped.count()));
}
}
Important classes and methods
FilterInputStreamis the JDK's base decorator: it stores the wrapped stream in a field and forwards every method.CountingInputStreamextends it and overrides the tworeadmethods to count bytes.- Writing uses four layers and reading uses six; each adds exactly one job.
Expected output
First line: 2026-11-02,store-001,orders=41
Lines read: 200
Bytes after unzip: 6200
Compressed bytes smaller than a tenth? true
How it runs
- 200 lines of 31 characters each are written: 6200 bytes before compression.
- The same counter class is placed twice, before and after
GZIPInputStream, to measure both sides. - The repetitive data compresses to less than a tenth of its size. The exact compressed size can differ between JDK builds, so the program prints a comparison instead of a number.
Real-World Enterprise Example: Configurable Payment Gateway Chain
Problem: payments must be screened for fraud, protected against duplicate charges when clients retry, and audited, and each environment enables a different mix of these features.
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.function.UnaryOperator;
public class PaymentDecoratorDemo {
record Payment(String idempotencyKey, String customerId, BigDecimal amount) { }
record Result(String status, String reference) { }
// Component
interface PaymentGateway {
Result charge(Payment payment);
}
// Concrete component: the real provider client
static final class ProviderGateway implements PaymentGateway {
private int sequence = 0;
@Override
public synchronized Result charge(Payment payment) {
sequence++;
System.out.println(" [provider] charging " + payment.amount() + " for " + payment.customerId());
return new Result("APPROVED", "TXN-" + sequence);
}
}
// Decorator 1: block risky amounts before they reach the provider
static final class FraudScreening implements PaymentGateway {
private final PaymentGateway next;
private final BigDecimal limit;
FraudScreening(PaymentGateway next, BigDecimal limit) { this.next = next; this.limit = limit; }
@Override
public Result charge(Payment payment) {
if (payment.amount().compareTo(limit) > 0) {
return new Result("HELD_FOR_REVIEW", "-");
}
return next.charge(payment);
}
}
// Decorator 2: the same idempotency key never charges twice
static final class Idempotent implements PaymentGateway {
private final PaymentGateway next;
private final Map<String, Result> seen = new ConcurrentHashMap<>();
Idempotent(PaymentGateway next) { this.next = next; }
@Override
public Result charge(Payment payment) {
return seen.computeIfAbsent(payment.idempotencyKey(), key -> next.charge(payment)); // atomic per key
}
}
// Decorator 3: record every attempt and outcome
static final class Auditing implements PaymentGateway {
private final PaymentGateway next;
private final List<String> auditLog;
Auditing(PaymentGateway next, List<String> auditLog) { this.next = next; this.auditLog = auditLog; }
@Override
public Result charge(Payment payment) {
Result result = next.charge(payment);
auditLog.add(payment.idempotencyKey() + " -> " + result.status() + " " + result.reference());
return result;
}
}
// Assemble the chain from configuration; the first feature listed is the outermost layer
static PaymentGateway build(List<String> features, PaymentGateway core, List<String> auditLog) {
Map<String, UnaryOperator<PaymentGateway>> decorators = Map.of(
"audit", g -> new Auditing(g, auditLog),
"idempotency", Idempotent::new,
"fraud", g -> new FraudScreening(g, new BigDecimal("100000")));
PaymentGateway gateway = core;
List<String> innerFirst = new ArrayList<>(features);
Collections.reverse(innerFirst);
for (String feature : innerFirst) {
gateway = decorators.get(feature).apply(gateway);
}
return gateway;
}
public static void main(String[] args) {
List<String> auditLog = new CopyOnWriteArrayList<>();
PaymentGateway gateway = build(List.of("audit", "idempotency", "fraud"), new ProviderGateway(), auditLog);
gateway.charge(new Payment("key-1", "C-17", new BigDecimal("2499.00")));
gateway.charge(new Payment("key-1", "C-17", new BigDecimal("2499.00"))); // client retried after a timeout
gateway.charge(new Payment("key-2", "C-17", new BigDecimal("250000.00"))); // above the fraud limit
gateway.charge(new Payment("key-3", "C-42", new BigDecimal("640.00")));
System.out.println("Audit log:");
auditLog.forEach(entry -> System.out.println(" " + entry));
}
}
Important classes and methods
FraudScreening,IdempotentandAuditingeach implementPaymentGatewayand wrap the next gateway.build()assembles the chain from a list of feature names, such as one read from configuration.IdempotentusescomputeIfAbsent(), so two threads with the same key cannot both reach the provider.- Shared state (the idempotency map and audit log) uses thread-safe collections, because one gateway chain serves all requests.
Expected output
[provider] charging 2499.00 for C-17
[provider] charging 640.00 for C-42
Audit log:
key-1 -> APPROVED TXN-1
key-1 -> APPROVED TXN-1
key-2 -> HELD_FOR_REVIEW -
key-3 -> APPROVED TXN-2
How it runs
- The chain is Auditing, then Idempotent, then FraudScreening, then the provider.
- The retried
key-1is answered from the idempotency map; the provider charges only once, and both attempts are audited. key-2is held by fraud screening and never reaches the provider.- Only two provider calls happen for four requests.
10. Best Practices and Common Mistakes
Best practices
- Keep each decorator to one responsibility, and keep the component interface small.
- Provide a base decorator that forwards everything, so concrete decorators override only what they change.
- Build chains in one place (a factory, builder or Spring configuration) and document the order.
- Thread safety: stateless decorators are safe to share. Stateful ones, such as caches, counters and dedup maps, need concurrent collections and atomic operations.
Common mistakes
- Ignoring order: insurance before or after fees, or auditing inside versus outside fraud checks, changes the result.
- Forgetting to forward a method, which silently skips the inner layers.
instanceofchecks on the concrete component, which fail once it is wrapped.- Overengineering: using decorators for one fixed feature that a simple method or subclass handles.
11. When to Use and When Not to Use
Use it when features are optional and combine freely, when behaviour must be chosen at runtime, or when you cannot or should not modify the original class.
Avoid it when the interface is large and every decorator must forward dozens of methods, when callers depend on the concrete type, or when a deep stack of wrappers would make stack traces and debugging painful.
12. Advantages and Disadvantages
Advantages
- Combines features freely without a subclass per combination.
- Runtime flexibility: chains can come from configuration.
- Open/Closed: new features are new classes.
- Small, testable classes with one job each.
Disadvantages
- Many small objects, and order-dependent behaviour.
- Identity changes: the outer object is not the original.
- Harder debugging through several layers.
13. Comparison with Similar Patterns
| Aspect | Decorator | Proxy | Adapter | Composite |
|---|---|---|---|---|
| Intent | Add responsibilities | Control access | Change the interface | Treat groups and single items alike |
| Interface | Same as the wrapped object | Same as the subject | Different from the adaptee | Same for leaves and groups |
| Wraps | One component, stackable | One subject, usually one layer | One adaptee | Many children |
| Who builds it | Client or configuration | Often a framework, hidden from the client | Integration code | The code that builds the tree |
Choose a Decorator to stack optional features, a Proxy to decide whether and when the real object is reached, an Adapter to fix an interface mismatch, and a Composite to treat a tree of objects as one. Strategy is the "inside" alternative: instead of wrapping an object, you swap a part of it.
14. Summary
- The decorator design pattern in Java wraps an object in layers that share its interface and add behaviour.
- Purpose: combine optional features without a subclass for every combination.
- Components: Component, Concrete Component, Base Decorator, Concrete Decorators.
- Each layer does its work and forwards the call inward; order affects the result.
- Used in
java.io, collection wrappers, servlet request wrappers and payment pipelines. - Benefits: runtime composition, Open/Closed design and small focused classes.
- Document the order, keep stateful decorators thread-safe, and avoid it for huge interfaces.
15. Java Design Pattern Interview Questions and Answers
Q1. The interface you need to decorate has 25 methods. How do you avoid writing 25 forwarding methods in every decorator?
Write the forwarding once in an abstract base decorator, like FilterInputStream does, and let concrete decorators extend it. Alternatives are a JDK dynamic proxy that intercepts only the methods you care about, or Lombok's experimental @Delegate. If many decorators are needed for a huge interface, consider splitting the interface.
Q2. After wrapping a JDBC connection in a decorator, a library's instanceof check fails. How do frameworks solve this?
They expose the wrapped object through an unwrap method. JDBC defines java.sql.Wrapper with isWrapperFor(Class) and unwrap(Class), which connection-pool wrappers implement. Code that needs the vendor class asks for it explicitly instead of using instanceof.
if (connection.isWrapperFor(PGConnection.class)) {
PGConnection pg = connection.unwrap(PGConnection.class);
}Q3. How can lambdas implement decorators?
When the component is a functional interface, a decorator is a function that takes one implementation and returns another. Function.andThen() and compose() chain behaviour the same way.
UnaryOperator<PaymentGateway> logging = next -> payment -> {
System.out.println("charging " + payment.amount());
return next.charge(payment);
};
PaymentGateway gateway = logging.apply(new ProviderGateway());Q4. How do you decorate a Spring bean that other beans inject by interface?
Register the original under a qualifier and expose the decorated version as the @Primary bean, so every injection point receives the decorator. For decorating many beans generically, a BeanPostProcessor can wrap them at startup.
@Bean @Qualifier("raw")
PaymentGateway providerGateway() { return new ProviderGateway(); }
@Bean @Primary
PaymentGateway paymentGateway(@Qualifier("raw") PaymentGateway raw) {
return new Auditing(new Idempotent(raw), auditLog());
}Q5. Your idempotency decorator works in tests but charges twice in production under load. What is likely wrong?
Probably a non-atomic check-then-act, such as if (!map.containsKey(key)) { charge(); map.put(...); } on a plain HashMap: two threads both see "missing" and both charge. Use ConcurrentHashMap.computeIfAbsent() within one instance. With several service instances, an in-memory map is not enough; store keys in a shared database or cache with a unique constraint.