How does "Proxy" differ from "Decorator"?
Proxy and Decorator look similar on the surface - both "wrap" an object and implement the same interface. But their goals and purposes differ.
1. Purpose
- Proxy controls access to an object. → decides when, how, and whether the real object can be called.
- Decorator extends the behavior of an object. → adds new functionality on top of the existing one.
2. Context of Use
| Situation | Proxy | Decorator |
|---|---|---|
| The object is heavy or remote | Lazy loading, cache | Not intended for this |
| Need to add new behavior (logging, encryption) | Possible, but not the main goal | The main goal |
| Access control / security | Yes | No |
| The client should think it is working with the "real object" | Mandatory | Not always |
3. An Example of the Difference
Proxy (access control):
java
class SecuredFileProxy implements FileAccess {
private RealFile realFile;
private String userRole;
public void read() {
if (userRole.equals("admin")) realFile.read();
else System.out.println("Access denied");
}
}Decorator (behavior extension):
java
class LoggingFileDecorator implements FileAccess {
private FileAccess wrappee;
public void read() {
System.out.println("Reading file...");
wrappee.read();
}
}4. Transparency
- Proxy aims to be unnoticeable: the client should not know it is working with an intermediary.
- Decorator is a deliberate wrapper: the client knows that new behavior has been added.
5. Analogy
- Proxy is like a guard at the door, deciding who gets in.
- Decorator is like a designer, decorating a room without changing its foundation.
Conclusion
| Criterion | Proxy | Decorator |
|---|---|---|
| Main purpose | Access control | Behavior extension |
| Transparency for the client | Full | Partial |
| Type of behavior | Controlling | Additive |
| Example | Lazy loading, protection, cache | Logging, encryption, formatting |
Summary: Proxy protects or controls, Decorator adds and decorates.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.