Senior
How does the GoF Mediator pattern differ from Proxy?
sobes.tech AI
Answer from AI
The Mediator and Proxy patterns solve different problems:
-
Mediator is a central object that manages interactions between multiple objects, reducing their coupling. Instead of objects communicating directly with each other, they interact through the mediator.
-
Proxy is a substitute object that controls access to another object, for example, for lazy initialization, access control, or caching.
Example:
- Mediator is used when coordinating complex interactions between components.
- Proxy is used when controlling access to a resource-intensive object.
// Mediator example
interface Mediator {
void notify(Component sender, String event);
}
class ConcreteMediator implements Mediator {
private Component1 c1;
private Component2 c2;
public void setComponent1(Component1 c1) { this.c1 = c1; }
public void setComponent2(Component2 c2) { this.c2 = c2; }
public void notify(Component sender, String event) {
if (sender == c1 && event.equals("A")) {
c2.doC();
}
}
}
// Proxy example
interface Image {
void display();
}
class RealImage implements Image {
private String filename;
public RealImage(String filename) { this.filename = filename; loadFromDisk(); }
private void loadFromDisk() { /* load file */ }
public void display() { /* display image */ }
}
class ProxyImage implements Image {
private RealImage realImage;
private String filename;
public ProxyImage(String filename) { this.filename = filename; }
public void display() {
if (realImage == null) {
realImage = new RealImage(filename);
}
realImage.display();
}
}