Let's take a good look at this sentence by following the code below.
proxy class, we use the proxy object to do some logging, we will briefly print information to the console.
Package Com.liang.pattern;public class Usermanagerimplproxy implements Usermanager {private Usermanager usermanager; Public Usermanagerimplproxy (Usermanager usermanager) {this.usermanager = Usermanager;} public void AddUser (string userId, String userName) { //record log operations or print input parameters System.out.println ("Start-->>adduser () userid-->> "+ userid"; Try{usermanager.adduser (userid, userName); Run successfully. Print success Information System.out.println ("Success-->>adduser ()");} catch (Exception e) {e.printstacktrace (); When it fails. Print failure Information System.out.println ("Error-->>adduser ()");//throw new RuntimeException ();}} public void Deluser (String userId) {//Ibid., slightly usermanager.deluser (userId);} public string Finduser (string userId) {//Ibid. Slightly usermanager.finduser (userId); return null;} public void ModifyUser (string userId, String userName) {//Ibid. Slightly Usermanager.modifyuser (userId, UserName);}}
Client Invocation
output results, this method runs successfully
Start-->>adduser () Userid-->>001usermanagerimpl.adduser () userid-->>001success-->> AddUser ()
from the class diagram we can see. The client would have been able to deal directly with the target object, with an indirect layer in the middle of the agent. The functions they implement are the same and do not change the number of parameters. I believe you are very familiar with the above class diagram and code. It's the same as our usual reading of other people's posts. No matter what the difference. Let's look at the pros and cons of static proxies.
Advantages and Disadvantages
Strengths :
1, the intuitive feeling, static agent is a real existence, we wrote.
2, in the compilation period to increase, in advance to specify who call who, high efficiency.
Disadvantages :
The same, its advantages have become its fatal disadvantage.
1, static agent is very troublesome. Requires a large number of proxy classes
When we have multiple target objects that need to be represented, I need to create multiple proxy classes. Change the original code, change the more it is very likely that the problem, you have to test again.
2, repeated code will appear in every corner now, contrary to a principle: repeated is not a good taste
We should stop repeating again and again.
3, increase in the compilation period, the system flexibility is poor
We can see that every method of the proxy class has a log, a successful or failed code, and each method repeats itself, assuming that we need to change it, and there is no place to reduce the change when we don't have a static proxy. Just don't change the target class. The dynamic agent is very good for us to overcome this problem. Let's look at the dynamic agent.
Dynamic Agent
Dynamic proxy class Diagram
Sample Code Demo
Proxy class (not clear, just look at it)
Package Com.liang.pattern;import Java.lang.reflect.invocationhandler;import Java.lang.reflect.method;import java.lang.reflect.proxy;/** * Using the JDK Dynamic agent must implement the Invocationhandler interface. Create the corresponding proxy class using the proxy class * @author Liang * */public class Proxyhandler implements Invocationhandler {private Object targetobject;/ * * The initialization method of the target. Generate proxy class based on target * @param targetObject * @return */public Object Newproxyinstance (Object targetObject) {this.targetobject = Targe tobject;//the first parameter, the target loader//The second parameter, the target interface, the agent//third parameter for each interface, the call implements the Invocationhandler object. When you call the proxy, the proxy invokes the Invocationhandler Invoke method return Proxy.newproxyinstance (Targetobject.getclass (). getClassLoader (), Targetobject.getclass (). Getinterfaces (), this);} /** * Reflection so that you can invoke a method of a class based on a configured parameter without knowing the detailed class.It's very practical when it comes to flexible programming. */public object Invoke (Object proxy, method, object[] args) throws Throwable {//record log operations or print input parameters System.out.println ( "Start-->>" + method.getname ()); for (int i=0;i<args.length;i++) {//Print call to target method System.out.println (Args[i]);} Object ret = null;try{//calls the target method ret = Method.invoke (targetObject, args);//Run successfully. Print success Information System.out.println ("success-->>" + method.getname ());} catch (Exception e) {e.printstacktrace ();//failed, print failure message System.out.println ("error-->>" + method.getname ()); throw e;} return ret;}}
Client Invocation
Output results, successful execution
Start-->>finduser0001usermanagerimpl.finduser () userid-->>0001success-->> Finduserclient.main-->> Concealed
interface and Target class, ditto, I will no longer waste everyone's bandwidth.
Advantages and Disadvantages
Strengths :
1, a dynamic proxy class is more simple, to solve the problem of creating multiple static agents, to avoid repeated redundant code
2, call the target code, will be in the method "execution" dynamic increase, determine what type you are, only adjust who, flexible
Disadvantages :
1, the system is flexible. However, the efficiency is reduced, a little slower than the static agent
2, dynamic agent than static proxy in the readability of the code a little bit, not too easy to understand
3, the JDK dynamic agent can only implement the interface of the class to proxy
Summarize
Static agent vs Dynamic Agent, played a tie, each has its own unique, can not be replaced, in the project exactly what kind of agent, no best. It's just more appropriate.