Sobes.tech
Junior — Middle

Explain the differences between decorator and proxy patterns and their use cases.

sobes.tech AI

Answer from AI

Decorator and Proxy patterns have a similar structure — both wrap an object and implement the same interface, but they differ in purpose and application.

Decorator:

  • Used for dynamically adding new responsibilities to an object without changing its code.
  • Allows extending the functionality of an object.
  • Example: adding logging, caching, validation on top of a basic service.

Proxy:

  • Controls access to an object, can manage creation, initialization, or protection.
  • Used for lazy loading, access control, remote calls.

Differences example:

  • Decorator adds behavior (e.g., wrapping input/output streams with encryption).
  • Proxy can check access rights before calling the real object's method.
interface Service {
    void execute();
}

// Decorator
class LoggingDecorator implements Service {
    private Service wrapped;
    public LoggingDecorator(Service s) { this.wrapped = s; }
    public void execute() {
        System.out.println("Before execution");
        wrapped.execute();
        System.out.println("After execution");
    }
}

// Proxy
class AccessProxy implements Service {
    private Service realService;
    public AccessProxy(Service s) { this.realService = s; }
    public void execute() {
        if (checkAccess()) {
            realService.execute();
        } else {
            throw new SecurityException("Access denied");
        }
    }
    private boolean checkAccess() { return true; /* access check logic */ }
}

In summary, decorator extends functionality, proxy controls access and management.

Explain the differences between decorator and proxy… - sobes.tech