What do Decorator and Wrapper have in common?
Decorator and Wrapper are almost the same in structure: in both cases an object is wrapped by another object that intercepts calls and adds extra behavior.
1. The Shared Idea
- Both patterns use composition: they hold a reference to the "wrapped" object internally.
- Both implement the same interface as the original, so the client does not notice a difference.
- Both delegate calls to the original object, adding something "on top".
2. An Example of the Shared Approach
java
class Wrapper implements Service {
private Service wrappee;
public Wrapper(Service s) { this.wrappee = s; }
public void execute() {
System.out.println("Before");
wrappee.execute();
System.out.println("After");
}
}This structure can be called either a decorator or a wrapper: the difference is only in the purpose.
3. Difference in Emphasis
| Criterion | Decorator | Wrapper |
|---|---|---|
| Purpose | Extend functionality | Isolate, simplify, or hide details |
| Used in | Design patterns | General programming |
| Semantics | "Add behavior" | "Wrap to control access, adapt, or protect" |
4. An Example of the Difference
- Decorator: adds logging, encryption, caching.
- Wrapper: hides the complexity of an API or a data format (for example,
HttpResponseWrapper).
Conclusion: A decorator is a special case of a wrapper, specialized in adding new behavior, while a wrapper is a more general term for any layer that intercepts and delegates calls to the underlying object.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.