Sobes.tech
Junior — Middle

Explain the differences between decorator, proxy, and adapter patterns in object-oriented programming.

sobes.tech AI

Answer from AI

Decorator, Proxy, and Adapter patterns solve different problems, although they all work with objects and interfaces:

  • Decorator — adds new functionality to objects dynamically by wrapping them. It allows extending behavior without modifying the original class.

  • Proxy — controls access to an object, can add logic when calling methods (e.g., lazy initialization, caching, security).

  • Adapter — transforms the interface of one class into the interface expected by the client. It is used for integrating incompatible interfaces.

Example in Java:

// Interface
interface Service {
    void operation();
}

// Implementation
class RealService implements Service {
    public void operation() {
        System.out.println("Performing operation");
    }
}

// Decorator
class Decorator implements Service {
    private Service wrappee;
    public Decorator(Service s) { this.wrappee = s; }
    public void operation() {
        System.out.println("Before operation");
        wrappee.operation();
        System.out.println("After operation");
    }
}

// Proxy
class Proxy implements Service {
    private RealService realService;
    public void operation() {
        if (realService == null) {
            realService = new RealService(); // lazy creation
        }
        realService.operation();
    }
}

// Adapter
class LegacyService {
    public void oldOperation() {
        System.out.println("Old method");
    }
}

class Adapter implements Service {
    private LegacyService legacy;
    public Adapter(LegacyService legacy) {
        this.legacy = legacy;
    }
    public void operation() {
        legacy.oldOperation();
    }
}
Explain the differences between decorator, proxy, and… - sobes.tech