Overview
The Proxy Design Pattern provides a surrogate or placeholder for another object to control access to it. It is often used to add a level of control, security, or additional functionality to object access.
Key Characteristics
- Controls access to a real object, providing an interface identical to the real object.
- Can add additional functionality such as caching, logging, or access control.
- Promotes the Single Responsibility Principle by separating the access logic from the real object.
Implementation
The following is an example of a Proxy implementation in Java:
// Subject interface
interface Image {
void display();
}
// Real Subject
class RealImage implements Image {
private String filename;
public RealImage(String filename) {
this.filename = filename;
loadImageFromDisk();
}
private void loadImageFromDisk() {
System.out.println("Loading " + filename);
}
@Override
public void display() {
System.out.println("Displaying " + filename);
}
}
// Proxy
class ProxyImage implements Image {
private RealImage realImage;
private String filename;
public ProxyImage(String filename) {
this.filename = filename;
}
@Override
public void display() {
if (realImage == null) {
realImage = new RealImage(filename);
}
realImage.display();
}
}
// Demo
public class ProxyDemo {
public static void main(String[] args) {
Image image1 = new ProxyImage("image1.jpg");
Image image2 = new ProxyImage("image2.jpg");
// Image will be loaded from disk
image1.display();
System.out.println("");
// Image will not be loaded from disk
image1.display();
System.out.println("");
// Image will be loaded from disk
image2.display();
}
}
When to Use
- When you need to control access to an object.
- When you want to add additional functionality like caching, logging, or access control without modifying the real object.
Advantages
- Provides controlled access to the real object.
- Can enhance performance through techniques like lazy initialization or caching.
- Promotes separation of concerns by handling access logic in the proxy.
Disadvantages
- Can introduce additional complexity to the design.
- May impact performance if the proxy adds significant overhead.