Junior — Middle
Explain the differences between adapter, decorator, and proxy patterns, their purposes, and areas of application.
sobes.tech AI
Answer from AI
The adapter, decorator, and proxy patterns solve different problems, although they all work with objects and interfaces.
-
Adapter — transforms the interface of a class into another interface expected by clients. Used when integrating incompatible interfaces.
-
Decorator — dynamically adds responsibilities to objects by wrapping them without changing the original class. Allows flexible extension of functionality.
-
Proxy — provides a surrogate or placeholder for another object, controlling access to it. Often used for lazy initialization, access control, or logging.
Example:
// Adapter
interface Target {
void request();
}
class Adaptee {
void specificRequest() { /*...*/ }
}
class Adapter implements Target {
private Adaptee adaptee = new Adaptee();
public void request() {
adaptee.specificRequest();
}
}
// Decorator
interface Component {
void operation();
}
class ConcreteComponent implements Component {
public void operation() { /* base implementation */ }
}
class Decorator implements Component {
protected Component component;
public Decorator(Component c) { this.component = c; }
public void operation() {
component.operation();
// additional behavior
}
}
// Proxy
class Proxy implements Subject {
private RealSubject realSubject;
public void request() {
if (realSubject == null) {
realSubject = new RealSubject();
}
realSubject.request();
}
}
Thus, the adapter changes the interface, the decorator extends behavior, and the proxy controls access to the object.