Proxy in Java
1. Introduction to Proxy Design Pattern
The Proxy Design Pattern is a structural design pattern that
provides a surrogate or placeholder for another object to control
access to it. In Java, proxies are often used to implement
functionalities like lazy loading, access control, logging, and
more.
2. Types of Proxies in Java
Java supports different types of proxies, including:
• - Virtual Proxy: Controls access to a resource that is
expensive to create.
• - Protective Proxy: Controls access rights to a resource based
on access permissions.
• - Remote Proxy: Represents an object in a different address
space.
• - Smart Proxy: Adds additional functionality like reference
counting, logging, etc.
3. Real-world Analogy
Imagine a celebrity who doesn't want to be contacted directly by
fans. A manager (proxy) handles communication. The fans contact
the manager, who decides whether to pass the message along.
Similarly, in programming, a proxy controls access to a resource.
4. Use Cases
• - Access control/security
• - Lazy initialization
• - Logging and auditing
• - Remote method invocation
5. Example Code (Static Proxy)
interface Service {
void performAction();
}
class RealService implements Service {
public void performAction() {
System.out.println("Real service is performing an
action");
}
}
class ProxyService implements Service {
private RealService realService = new RealService();
public void performAction() {
System.out.println("Proxy in action - Access granted");
realService.performAction();
}
}
public class Main {
public static void main(String[] args) {
Service service = new ProxyService();
service.performAction();
}
}
6. Advantages and Disadvantages
• Advantages:
• - Controls access to the original object
• - Adds additional functionality without changing actual
code
• Disadvantages:
• - Adds complexity to the code
• - May introduce latency if not implemented properly
7. Summary
The Proxy pattern in Java is a powerful concept used to manage
access to objects. By using proxies, developers can introduce
additional behavior like logging, security checks, and lazy
loading without modifying the actual business logic.