Skip to main content

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

SituationProxyDecorator
The object is heavy or remoteLazy loading, cacheNot intended for this
Need to add new behavior (logging, encryption)Possible, but not the main goalThe main goal
Access control / securityYesNo
The client should think it is working with the "real object"MandatoryNot 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

CriterionProxyDecorator
Main purposeAccess controlBehavior extension
Transparency for the clientFullPartial
Type of behaviorControllingAdditive
ExampleLazy loading, protection, cacheLogging, encryption, formatting

Summary: Proxy protects or controls, Decorator adds and decorates.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.