# Purpose
The Proxy pattern provides a substitute for an object to control access, postpone its creation or perform additional actions (lazy loading, validation, etc.).
We can see it as a representative that acts as an intermediary with the real object.
# Problem
-
Access Control: Restrict who accesses the object.
-
Creation Costs: Postpone creation of heavy objects (lazy loading).
-
Remote References: Work with objects in other memory spaces.
# Solution
The solution proposed by Proxy is:
-
Substitution: Intermediary with an identical interface to the real object.
-
Control: Adds validation, lazy loading or security before delegating.
# Structure
# Participants
- Subject: Common interface for Proxy and RealSubject.
- RealSubject: The object that performs the real operation.
- Proxy: Representative that controls access.
- Client: Uses the intermediary.
# When to Use It
-
Need for strict access control.
-
Management of expensive operations on demand.
# Advantages
-
verified
Separation of responsibilities: Logging, security, etc., isolated.
-
verified
Performance: Lazy loading and efficient connection management.
# Disadvantages
-
warning
Delay: Intermediary can introduce delay.
-
warning
Complexity: Extra layer of abstraction.
# Example: HD Images
We manage high resolution images. They are heavy and loading them all at startup is not efficient.
# Java Code
class ImageProxy implements Image {
private HighResImage realImage;
public void display() {
if (realImage == null) realImage = new HighResImage(path);
realImage.display();
}
}
public class Client {
public static void main(String[] args) {
Image img = new ImageProxy("photo.jpg");
img.display(); // File is loaded only here
}
}
# Mapping Participants
- Image (Subject): Common interface.
- HighResImage (RealSubject): Expensive operation.
- ImageProxy: Substitute with lazy loading.
# Conclusions
Efficient solution to manage expensive resources, loading them only when necessary, improving performance and user experience.
# Related Patterns
Adapter
Provides a different interface; Proxy provides the same.
Decorator
Adds responsibilities; Proxy acts as an access intermediary.