Decorator Pattern Implementation in Java
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Decorator Pattern runs in O(1) time and O(n) space, in Java as in every other language.
- ✓java.io is the textbook implementation and the reason most Java developers meet this pattern first: FilterInputStream and FilterOutputStream are decorator base classes, and BufferedInputStream, GZIPInputStream, DataInputStream and CipherInputStream all wrap another stream with the same interface.
- ✓Extend the provided Filter base class when decorating java.io types so you inherit the forwarding and override only what changes.
- ✓The Java trap: Closing the wrong layer of a java.io chain silently loses data: a BufferedOutputStream holds bytes in memory, so closing the underlying FileOutputStream instead of the buffer discards whatever had not been flushed, the file is short and no exception is thrown.
- ✓A hand-written decorator is an ordinary virtual call the JIT inlines away when the chain is monomorphic, so stacking three static decorators is effectively free after warm-up.
What Decorator Pattern actually is
Decorator Pattern in Java: what you actually reach for
Java implementation
import java.io.*;
public final class Streams {
public static void write(File f, byte[] data) throws IOException {
// Chain order matters, and so does WHICH one you close.
try (OutputStream out =
new BufferedOutputStream(
new java.util.zip.GZIPOutputStream(
new FileOutputStream(f)))) {
out.write(data);
} // closing the OUTERMOST cascades and flushes the buffer
}
// Closing the inner stream instead loses everything still buffered,
// with NO exception:
//
// FileOutputStream file = new FileOutputStream(f);
// BufferedOutputStream buf = new BufferedOutputStream(file);
// buf.write(data);
// file.close(); // truncated file, silently
}
/** Forwarding base so each concrete decorator stays short. */
abstract class ForwardingStore implements Store {
protected final Store delegate;
protected ForwardingStore(Store delegate) { this.delegate = delegate; }
@Override public String get(String key) { return delegate.get(key); }
@Override public void set(String key, String value) { delegate.set(key, value); }
}
interface Store {
String get(String key);
void set(String key, String value);
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Java-specific trap
Performance in Java, beyond the O(1)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Java type or library should I use for Decorator Pattern?
java.io is the textbook implementation and the reason most Java developers meet this pattern first: FilterInputStream and FilterOutputStream are decorator base classes, and BufferedInputStream, GZIPInputStream, DataInputStream and CipherInputStream all wrap another stream with the same interface. For interface-wide interception without writing forwarding methods, java.lang.reflect.Proxy generates a decorator at runtime from an InvocationHandler.
What is the most common Java mistake when implementing Decorator Pattern?
Closing the wrong layer of a java.io chain silently loses data: a BufferedOutputStream holds bytes in memory, so closing the underlying FileOutputStream instead of the buffer discards whatever had not been flushed, the file is short and no exception is thrown. Close the outermost wrapper, which cascades. The second trap is that java.lang.reflect.Proxy only works for INTERFACES, so a decorator over a concrete class needs bytecode generation (Byte Buddy, or Spring CGLIB proxies) instead, and CGLIB proxies cannot intercept final or private methods, a Spring @Transactional annotation on a private method silently does nothing.
How does Decorator Pattern actually perform in Java?
A hand-written decorator is an ordinary virtual call the JIT inlines away when the chain is monomorphic, so stacking three static decorators is effectively free after warm-up. Dynamic proxies are not: each call goes through InvocationHandler.invoke with an Object[] argument array, boxing primitives and defeating inlining, which is typically an order of magnitude slower and is why frameworks reserve proxies for coarse operations like a transactional service method rather than fine-grained calls. Time complexity is O(1) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialStudying for this? GitHub Copilot free tiers and academic plans are laid out on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.