The intent of Proxy Pattern is to provide a placeholder for an object to control access to it, and add a wrapper and delegation to protect the real component from undue complexity.
The reason to need the placeholder is sometimes we want to control the access to the target object due to different reasons, such as
1) it is expensive to create an object
2) giving different access rights to an object
3) access remote object
Here is the basic flow of proxy pattern:
- Create a proxy for a target
- Encapsulate the complexity/overhead of the target in the proxy
- The client deals with the proxy, and the proxy delegates the request to the target
Implementation
The figure below shows a UML class diagram for Proxy Pattern
A proxy client obtains a reference to a proxy (ProxySubject), the client then handles the proxy in the same way it handles RealSubject and thus invoking the method operation(). In ProxySubject operation method can add different logic to control if it invokes RealSubject operation method.
Step 1: create a subject interface
1 2 3 4 5 6 7 |
package net.tecbar.designpattern.proxy; public interface Subject { void operation(); } |
Step 2: create RealSubject class
1 2 3 4 5 6 7 8 9 10 11 12 |
package net.tecbar.designpattern.proxy; public class RealSubject implements Subject { @Override public void operation() { System.out.println("the real subject was executed"); } } |
Step 3: create a Proxy class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
package net.tecbar.designpattern.proxy; public class ProxySubject implements Subject { private RealSubject realSubject; @Override public void operation() { System.out.println("the proxy subject was called"); // you add add logic to control if invoke RealSubject operation method if(realSubject == null) { realSubject = new RealSubject(); } realSubject.operation(); } } |
Step 4: create a client
1 2 3 4 5 6 7 8 9 10 |
package net.tecbar.designpattern.proxy; public class ProxyClient { public static void main(String[] args) { Subject subject = new ProxySubject(); subject.operation(); // call proxy, but real subject will be executed } } |
Pingback: Software Design Patterns