Proxy Design Pattern
Intent
Provide a surrogate or placeholder for another object to control access to it.Also known as
SurrogateExplanation
Real world example
Imagine a tower where the local wizards go to study their spells. The ivory tower can only be accessed through a proxy which ensures that only the first three wizards can enter. Here the proxy represents the functionality of the tower and adds access control to it.In plain words
Using the proxy pattern, a class represents the functionality of another class.Wikipedia says
A proxy, in its most general form, is a class functioning as an interface to something else. A proxy is a wrapper or agent object that is being called by the client to access the real serving object behind the scenes. Use of the proxy can simply be forwarding to the real object, or can provide additional logic. In the proxy extra functionality can be provided, for example caching when operations on the real object are resource intensive, or checking preconditions before operations on the real object are invoked.Structure
Participants
1. Proxy- Maintains a reference that lets the proxy access the real subject.
- Proxy may refer to a Subject if the RealSubject and Subject interfaces are the same.
- Provides an interface identical to Subject's so that a proxy can by substituted for the real subject.
- Controls access to the real subject and may be responsible for creating and deleting it.
2. Subject
- Defines the common interface for RealSubject and Proxy so that a Proxy can be used anywhere a RealSubject is expected.
- Defines the real object that the proxy represents.
Collaborations
- Proxy forwards requests to RealSubject when appropriate, depending on the kind of proxy.
Advantage of Proxy Pattern
- It provides the protection to the original object from the outside world.
Source code (First Example)
Let's create a sample Students registration for course with it's batch size is 10.Create a proxy object which does control accessing to the student enrollment to batch. It does not allow more than 10 students to enroll to course.
Step 1 : Create interface Batch (It acts as Subject refer to structure)
/**
*
* Batch interface.
*
*/
public interface Batch {
int totalStudents();
void registerStudent(String name);
}
Step 2 : Create RealObject that is CourseBatch which implements Batch interface.
/**
*
* The object to be proxyed.
*
*/
public class CourseBatch implements Batch{
private List<String> listOfStudents;
public CourseBatch(){
listOfStudents = new ArrayList<>();
}
@Override
public int totalStudents() {
return listOfStudents.size() + 1;
}
@Override
public void registerStudent(String name) {
listOfStudents.add(name);
System.out.println(" Student name : " + name);
}
}
Step 3 : The proxy class controlling access to the CourseBatch.
/**
* The proxy class controlling access to the CourseBatch.
*
*/
public class ProxyBatch implements Batch{
private Batch batch;
private static final int TOTAL_STUDENTS_ALLOWED_TO_BATCH = 10;
public ProxyBatch(Batch batch) {
this.batch = batch;
}
@Override
public int totalStudents() {
return batch.totalStudents();
}
@Override
public void registerStudent(String name) {
if(TOTAL_STUDENTS_ALLOWED_TO_BATCH >= this.totalStudents()){
batch.registerStudent(name);
}else{
System.out.println("Course batch size is : " + TOTAL_STUDENTS_ALLOWED_TO_BATCH);
System.out.println("Batch is full so further students are not allowed ");
}
}
}
Step 4 : Let's test the proxy design pattern.
The Proxy design pattern allows you to provide an interface to other objects by creating a wrapper class as the proxy. The wrapper class, which is the proxy, can add additional functionality to the object of interest without changing the object's code.
In this example the proxy ProxyBatch controls access to the actual object courseBatch.
public class TestProxyPattern {
public static void main(String[] args) {
Batch courseBatch = new CourseBatch();
Batch proxyBatch = new ProxyBatch(courseBatch);
proxyBatch.registerStudent(" student 1");
proxyBatch.registerStudent(" student 2");
proxyBatch.registerStudent(" student 3");
proxyBatch.registerStudent(" student 4");
proxyBatch.registerStudent(" student 5");
proxyBatch.registerStudent(" student 6");
proxyBatch.registerStudent(" student 7");
proxyBatch.registerStudent(" student 8");
proxyBatch.registerStudent(" student 9");
proxyBatch.registerStudent(" student 10");
proxyBatch.registerStudent(" student 11");
proxyBatch.registerStudent(" student 12");
proxyBatch.registerStudent(" student 13");
}
}
Output :
Student name : student 1
Student name : student 2
Student name : student 3
Student name : student 4
Student name : student 5
Student name : student 6
Student name : student 7
Student name : student 8
Student name : student 9
Student name : student 10
Course batch size is : 10
Batch is full so further students are not allowed
Course batch size is : 10
Batch is full so further students are not allowed
Course batch size is : 10
Batch is full so further students are not allowed
Source code (Second example)
Imagine a tower where the local wizards go to study their spells. The ivory tower can only be accessed through a proxy which ensures that only the first three wizards can enter. Here the proxy represents the functionality of the tower and adds access control to it.
Taking our wizard tower example from above. Firstly we have the wizard tower interface and the ivory tower class.
public interface WizardTower {
void enter(Wizard wizard);
}
public class IvoryTower implements WizardTower {
private static final Logger LOGGER = LoggerFactory.getLogger(IvoryTower.class);
public void enter(Wizard wizard) {
LOGGER.info("{} enters the tower.", wizard);
}
}
Then a simple wizard class
public class Wizard {
private final String name;
public Wizard(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
}
Then we have the proxy to add access control to wizard tower
public class WizardTowerProxy implements WizardTower {
private static final Logger LOGGER = LoggerFactory.getLogger(WizardTowerProxy.class);
private static final int NUM_WIZARDS_ALLOWED = 3;
private int numWizards;
private final WizardTower tower;
public WizardTowerProxy(WizardTower tower) {
this.tower = tower;
}
@Override
public void enter(Wizard wizard) {
if (numWizards < NUM_WIZARDS_ALLOWED) {
tower.enter(wizard);
numWizards++;
} else {
LOGGER.info("{} is not allowed to enter!", wizard);
}
}
}
And here is tower entering scenario
WizardTowerProxy proxy = new WizardTowerProxy(new IvoryTower());
proxy.enter(new Wizard("Red wizard")); // Red wizard enters the tower.
proxy.enter(new Wizard("White wizard")); // White wizard enters the tower.
proxy.enter(new Wizard("Black wizard")); // Black wizard enters the tower.
proxy.enter(new Wizard("Green wizard")); // Green wizard is not allowed to enter!
proxy.enter(new Wizard("Brown wizard")); // Brown wizard is not allowed to enter!
Proxy pattern is used in different use cases . Lets see the Remote proxy and Virtual proxy.
Remote Proxy
Virtual Proxy
Applicability
Proxy is applicable whenever there is a need for a more versatile or sophisticated reference to an object than a simple pointer. Here are several common situations in which the Proxy pattern is applicable- Remote proxy provides a local representative for an object in a different address space.
- Virtual proxy creates expensive objects on demand.
- Protection proxy controls access to the original object. Protection proxies are useful when objects should have different access rights.
Typical Use Case
- Control access to another object
- Lazy initialization
- Implement logging
- Facilitate network connection
- Count references to an object
Real world examples
- Mocking frameworks Mockito, Powermock, EasyMock
Comments
Post a Comment