Junior — Middle
Can you explain the concept of the proxy pattern and its purpose in programming?
sobes.tech AI
Answer from AI
The "Proxy" pattern is a structural design pattern that provides a surrogate object for another object. The proxy controls access to the real object, allowing additional actions to be performed when methods are called.
Purpose of the proxy:
- Lazy initialization (lazy loading).
- Access control (e.g., permission checks).
- Logging calls.
- Caching results.
- Remote access (e.g., in RMI).
Example in Java:
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); // load on first call
}
realImage.display();
}
}
// Usage:
Image image = new ProxyImage("photo.jpg");
image.display(); // loads and displays
image.display(); // just displays
Here, ProxyImage delays loading the actual image until the first call to display().