GoF Definition: Provide a surrogate or placeholder for another object to control access to it.
We want to use a class which can perform as an interface to something else.
In a classroom, when one student is absent, during roll call, his best friend may try to mimic the student’s voice to try to keep his friend from being marked as absent.
Consider an ATM implementation for a bank. Here we will find multiple proxy objects. Actual bank information will be stored in a remote server. We must remember that in the real programming world, the creation of multiple instances of a complex object (heavy object) is very costly. In such situations, we can create multiple proxy objects (which must point to an original object) and the total creation of actual objects can be carried out on a demand basis. Thus we can save both the memory and creational time.
In the following program, we are calling the doSomework() function of the proxy object, which in turn calls the doSomework() of the concrete object. With the output, we are getting the result directly through the concrete object.
In this example we have followed this structure. Related parts are separated by the packages for better readability. Our concrete or original implementations reside in the package OriginalClasses, Proxy implementation (Proxy.java) is in the package ProxyClasses. A proxy is created and tested in ProxyPatternEx.java.
High-level structure of the parts of the program is as follows:
// Subject.java
package OriginalClasses;
public abstract class Subject
{
public abstract void doSomeWork();
}
// ConcreteSubject.java
package OriginalClasses;
import OriginalClasses.Subject;
public class ConcreteSubject extends Subject
{
@Override
public void doSomeWork()
{
System.out.println(" I am from concrete subject");
}
}
// Proxy.java
package ProxyClasses;
import OriginalClasses.*;
public class Proxy extends Subject
{:
ConcreteSubject cs;
@Override
public void doSomeWork()
{
System.out.println("Proxy call happening now");
//Lazy initialization
if (cs == null)
{
cs = new ConcreteSubject();
}
cs.doSomeWork();
}
}
// ProxyPatternEx.java
package proxy.pattern.demo;
import ProxyClasses.Proxy;
class ProxyPatternEx
{
public static void main(String[] args)
{
System.out.println("***Proxy Pattern Demo*** ");
Proxy px = new Proxy();
px.doSomeWork();
}
}
What are the different types of proxies?
Mainly we are familiar with the following types:
Remote proxies. They will hide that actual object which is in a different address space.
Virtual proxies. They are used to perform optimization techniques like the creation of a heavy object on a demand basis.
Protection proxies. They generally deal with different access rights.
Smart reference. It can also perform some additional housekeeping work when an object is accessed. A typical operation is counting the number of references to the actual object.