🧩Proxy Pattern – Overview
🧠 Concept
🧱 Key Roles
Role
Description
💻 Java Example – Image Loading Example
// ----- Subject -----
interface Image {
void display();
}
// ----- Real Subject -----
class RealImage implements Image {
private String filename;
public RealImage(String filename) {
this.filename = filename;
loadFromDisk();
}
private void loadFromDisk() {
System.out.println("Loading image from disk: " + filename);
}
public void display() {
System.out.println("Displaying: " + filename);
}
}
// ----- Proxy -----
class ProxyImage implements Image {
private String filename;
private RealImage realImage;
public ProxyImage(String filename) {
this.filename = filename;
}
public void display() {
// Lazy loading — only load when needed
if (realImage == null) {
realImage = new RealImage(filename);
}
realImage.display();
}
}
// ----- Client -----
public class Main {
public static void main(String[] args) {
Image image = new ProxyImage("photo.png");
// Image not loaded yet
System.out.println("First display:");
image.display();
// Cached object used (no reload)
System.out.println("\nSecond display:");
image.display();
}
}🧠 Flow Summary
Step
Action
Behavior
🪜 Summary
🧾 Real-world Analogy
🧭 TL;DR
Last updated