The Proxy and Facade patterns are structural design patterns in object-oriented programming, and they serve different purposes:
Proxy Pattern
- Purpose: The Proxy pattern provides a placeholder for another object to control access to it. It is often used to add a layer of security, lazy initialization, logging, or to manage resource-intensive objects.
- Example:
interface Image {
void display();
}
class RealImage implements Image {
private String fileName;
public RealImage(String fileName) { this.fileName = fileName; loadFromDisk();
}
private void loadFromDisk() {
System.out.println("Loading " + fileName);
}
public void display() {
System.out.println("Displaying " + fileName); }
}
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();
}
}
Facade Pattern
- Purpose: The Facade pattern provides a simplified interface to a complex subsystem. It hides the complexities of the subsystem from the client, making the interface easier to use.
- Example:
class CPU {
public void start() { System.out.println("CPU started");
}
}
class Memory {
public void load() { System.out.println("Memory loaded"); }
}
class HardDrive {
public void readData() { System.out.println("Data read from hard drive");
}
}
class ComputerFacade {
private CPU cpu;
private Memory memory;
private HardDrive hardDrive;
public ComputerFacade() {
this.cpu = new CPU();
this.memory = new Memory();
this.hardDrive = new HardDrive();
}
public void startComputer() {
cpu.start();
memory.load();
hardDrive.readData();
} }
Summary:
- Proxy controls access to an object, often adding behavior before or after the actual object’s method execution.
- Facade simplifies interaction with a complex system by providing a unified, easy-to-use interface.

Hinterlasse einen Kommentar