"Java Project Combat" proxy pattern, static proxy VS dynamic Agent

Source: Internet
Author: User


This blog post, we mainly in the form of class diagram and code to learn about static agents and dynamic agents. Focus on their strengths and weaknesses.


Defined


Proxy pattern is the structural pattern of an object, which provides a proxy object to an object and controls the reference to the original object by the proxy object.


Proxy mode does not change the original interface and behavior, just the agent to do something, the agent can control the original target, such as: agents, agents will only buy things, but will not change behavior. Don't make things.

Let's take a good look at this sentence by following the code below.


Classification


Static agents and dynamic proxies


Static proxy


Static proxy class diagram



Sample Code Demo



Interface

Package Com.liang.pattern;public interface Usermanager {public void AddUser (String userid,string userName);p ublic void Deluser (string userid);p ublic void ModifyUser (String userid,string userName);p ublic string Finduser (string userid);

target Object

Package Com.liang.pattern;public class Usermanagerimpl implements Usermanager {public void AddUser (string userId, String UserName) {try{system.out.println ("Usermanagerimpl.adduser () userid-->>" + userId);} catch (Exception e) {e.printstacktrace (); throw new RuntimeException ();}} public void Deluser (String userId) {System.out.println ("Usermanagerimpl.deluser () userid-->>" + userId);} public string Finduser (string userId) {System.out.println ("Usermanagerimpl.finduser () userid-->>" + userId); Return "to Light";} public void ModifyUser (string userId, String userName) {System.out.println ("Usermanagerimpl.modifyuser () userid--> > "+ userId);}}

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.



"Java Project Combat" proxy pattern, static proxy VS dynamic Agent

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.