Proxy Pattern
Proxy patterns creates a representative or placeholder object to another object.
This helps in controlling access to a remote or expensive object.
Proxy example
First, we create Subject interface for both the Real Subject and Proxy.
package com.topjavatutorial.patterns.proxy; public interface Subject { void doSomething(); }
Next, lets create a RealSubject class that implements the Subject and does some real work.
package com.topjavatutorial.patterns.proxy; public class RealSubject implements Subject { @Override public void doSomething() { System.out.println("Real object.. Doing some real work !!"); } }
The Proxy provides controlled access to the RealSubject. We create a Proxy class that holds a reference to the RealSubject.
package com.topjavatutorial.patterns.proxy; public class Proxy implements Subject { RealSubject rs; @Override public void doSomething() { System.out.println("Proxy object.. calling real object"); if(rs == null){ rs = new RealSubject(); } rs.doSomething(); } }
To execute this program, we’ll create a ProxyDemo class that creates a Proxy instance and executes the doSomething() method. The Proxy in turn invokes this method on the RealSubject.
package com.topjavatutorial.patterns.proxy; public class ProxyDemo { public static void main(String[] args) { Proxy proxy = new Proxy(); proxy.doSomething(); } }
Output
Proxy object.. calling real object
Real object.. Doing some real work !!
Proxy variations
Remote Proxy
A remote proxy controls access to a remote object
Virtual Proxy
A virtual proxy controls access to a resource that is difficult to create
Protection Proxy
A protection proxy controls access to a resource based on access rights.
Difference between Proxy and Decorator
A Proxy controls access to an object. Client can use it as a stand-in for a real subject, as it can protect the real subject from unwanted access. A Decorator decorates the object by adding additional behavior.
Proxy can instantiate the real subject whereas Decorator only provides additional behavior to the subject and doesn’t instantiate it.
Reference books
Head First Object-Oriented Analysis and Design
© 2016, https:. All rights reserved. On republishing this post, you must provide link to original post