Overview
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.But, in some circumstances, it is useful to dynamically generate the bytecodes for the proxy class at runtime. This module will look at the techniques for dynamically generating proxies in Java and the benefits of doing so.
Proxy objects are useful in many situations to act as an intermediary between a client object and a target object.
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.
Ways that proxies can provide access control include:
1. Synchronization
2. Authentication
3. Remote Access
4. 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()

- 大小: 15.9 KB

- 大小: 23 KB
分享到:
相关推荐
4. **动态代理(Dynamic Proxies)**:增强了动态代理机制,使得创建动态代理类更加灵活,便于实现AOP(面向切面编程)。 5. **Swing增强**:JDK 1.6对Swing库进行了更新,提供了更好的UI外观和行为,例如Metal主题...
3. New Features and Enhancements in Spring Framework 4.0 ............................................ 17 3.1. Improved Getting Started Experience .........................................................
3. New Features and Enhancements in Spring Framework 4.0 ............................................ 17 3.1. Improved Getting Started Experience .........................................................