Proxy objects are useful in many situations to act as an intermediary between a client object and a target object Usually, the proxy class is already available as Java bytecodes, having been compiled from the Java source file for the proxy class When needed, the bytecodes for the proxy class are loaded into the Java Virtual Machine and proxy objects can then be instantiated
Now let's have the client interact with the target object through a proxy
Remember that the main intent of a proxy is to control access to the target object, rather than to enhance the functionality of the target object
The ways that proxies can provide access control include:
=> Synchronization
=>Authentication
=>Remote Access
=>Lazy instantiation
Here's our VehicleProxy class:
/**
* Class VehicleProxy.
*/
public class VehicleProxy implements IVehicle {
private IVehicle v;
public VehicleProxy(IVehicle v) {this.v = v;}
public void start() {
System.out.println("VehicleProxy: Begin of start()");
v.start();
System.out.println("VehicleProxy: End of start()");
}
// stop(), forward(), reverse() implemented similarly.
// getName() not shown.
}
/**
* Class Client2.
* Interacts with a Car Vehicle through a VehicleProxy.
*/
public class Client2 {
public static void main(String[] args) {
IVehicle c = new Car("Botar");
IVehicle v = new VehicleProxy(c);
v.start();
v.forward();
v.stop();
}
}
Output for the vehicle example with a proxy:
VehicleProxy: Begin of start()
Car Botar started
VehicleProxy: End of start()
VehicleProxy: Begin of forward()
Car Botar going forward
VehicleProxy: End of forward()
VehicleProxy: Begin of stop()
Car Botar stopped
VehicleProxy: End of stop()