Senior
How does the GoF Mediator pattern differ from the Proxy pattern?
sobes.tech AI
Answer from AI
The Mediator and Proxy patterns solve different problems and have different goals:
-
Mediator is a behavioral pattern that centralizes interaction between objects. Instead of objects interacting directly with each other, they communicate through a mediator, which coordinates their work. This reduces coupling between components and simplifies managing complex interactions.
-
Proxy is a structural pattern that provides a surrogate or substitute for another object, controlling access to it. A proxy can add additional logic (such as lazy initialization, caching, access control) without modifying the original object.
Key differences:
- The Mediator manages interaction among multiple objects, acting as a central coordinator.
- The Proxy controls access to a single object, acting as its representative.
Example:
// Mediator
interface Mediator {
void notify(Component sender, String event);
}
class ConcreteMediator implements Mediator {
private Component1 c1;
private Component2 c2;
public void setComponents(Component1 c1, Component2 c2) {
this.c1 = c1;
this.c2 = c2;
}
@Override
public void notify(Component sender, String event) {
if (event.equals("A")) {
c2.doC();
} else if (event.equals("B")) {
c1.doD();
}
}
}
// Proxy
interface Service {
void request();
}
class RealService implements Service {
public void request() {
System.out.println("Executing request");
}
}
class ProxyService implements Service {
private RealService realService;
public void request() {
if (realService == null) {
realService = new RealService(); // lazy creation
}
System.out.println("Proxy: additional logic before call");
realService.request();
}
}