A proxy is a commonly used programming pattern, like a network proxy, where the proxy is an intermediate object between the caller and the true calling target object, and the agent provides some additional or different actions when invoking the true target object, and the actual operation of the target object or the target object is done through the proxy invocation.
A simple proxy example is as follows:[Java] View plain copy//interface interface interface{ void DoSomething (); void somethingelse (string arg); } //target object class realobject implement interface{ public void dosomething () { System.out.println ("realobject dosomething"); } Public void somethingelse (String arg) { system.out.println ("realobject somethingelse " + arg) ; } } //Simple proxy objects class simpleproxy implements Interface ( private Interface proxied; public simpleproxy (interface proxied) { this.proxied = proxied; } public void dosomething () { system.out.println ("simpleproxy dosomething"); proxied.dosomething (); } public void somethingelse (String arg) { system.out.println ("simpleproxy somethingelse " + arg); proxied.somethingelse (ARG); } ) class simpleproxydemo{ public static void Consumer (interface iface) { iface.dosomething () ; iface.somethingelse ("TestProxy"); } Public static void main (String[] args) { //Not with Agent cOsumer (New realobject ()); //use agent Cosumer (New simpleproxy (New realobject ())); } }
The output results are:
Realobject dosomething
Realobjectsomethingelse Testproxy
Simpleproxy dosomething
Realobject dosomething
Simpleproxy SomethingElse Testproxy
Realobject SomethingElse Testproxy
The example above shows that agent Simpleproxy has done some extra work before calling the target object method.
The proxy in Java is a dynamic proxy for the interface, and of course Java can use a third-party cglib to implement the proxy for the class, but the JDK only supports dynamic proxies for the interfaces, we only analyze the dynamic agents of the JDK.
Elements of the JDK dynamic proxy:
(1). Implements the Invocationhandler proxy processing class, implements its Invoke method, this method is the proxy invokes the target object method and provides the extra operation the method.
(2). Use Proxy.newproxyinstance (class loader, Proxy interface list, Invocationhandler object); method creates a dynamic proxy that implements the specified interface.
The proxy example for JDK is as follows: [Java] View plain copy//interface interface interface{ & Nbsp; void dosomething (); void somethingelse ( STRING ARG); } //target object class realobject implement interface{