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

Source: Internet
Author: User
Tags repetition


This blog post, we mainly in the form of class diagram and code to learn about static agents and dynamic agents, focusing on the advantages and disadvantages of each.


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.


Classification


Static agents and dynamic proxies


Static proxy


Static proxy class diagram



code Example



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 object, we use the proxy object to do some logging, we print the brief 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-->>ad                Duser () userid-->> "+ userid"; Try{usermanager.adduser (userid, userName); Successful execution, print success information System.out.println ("Success-->>adduser ()");}                catch (Exception e) {e.printstacktrace (); Failed, print failure message 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 Calls


output result, this method executes successfully

Start-->>adduser () Userid-->>001usermanagerimpl.adduser () userid-->>001success-->> AddUser ()

from the class diagram we can see that the client can be directly with the target object, the agent in the middle of an indirect layer, they realize the function is the same, and did not change the parameters. I believe you are familiar with the above class diagram and code, and we usually look at other people's blog, no difference, the following we look at the advantages and disadvantages of static agents.


Advantages and Disadvantages


Advantages :

1, the intuitive feeling, static agent is a real existence, we wrote.

2, in the compilation period to join, early on the designation of who call who, high efficiency.


Disadvantages :

Also, its advantages have become its fatal disadvantage.

1, static agent is troublesome, need a large number of proxy class

When we have more than one target object need to proxy, I need to set up a number of proxy classes, change the original code, changed more is likely to be a problem, it must be re-tested.

2, repeated code will appear in various corners, contrary to a principle: repetition is not a good taste

We should eliminate repetition again and again.

3, in the compilation period, the system flexibility is poor



Let's look at the dynamic agent.


Dynamic Agent


Dynamic proxy class Diagram



code example



Proxy class (Don't understand, just look at the comments)

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, using the proxy class to create the corresponding proxy class * @author Liang * */public class Proxyhandler implements Invocationhandler {private Object targetobject;/** * Proxy initialization method * @param targetObject * @return */pu Blic Object Newproxyinstance (Object targetObject) {this.targetobject = targetobject;//first parameter, target class loader//second parameter, interface of target object// The third parameter, call implements the Invocationhandler object, when you call the proxy, the proxy will call Invocationhandler's 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 the configured parameters without knowing the specific class. Very useful in 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 the parameter of the target method System.out.println (Args[i]);} Object ret = null;try{//call to target method ret = Method.invoke (targetobjECT, args);//successful execution, 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 Calls


Output results, run successfully

Start-->>finduser0001usermanagerimpl.finduser () userid-->>0001success-->> Finduserclient.main-->> Concealed


interface and Target class, ditto, I will no longer waste everyone's bandwidth.


Advantages and Disadvantages
Advantages :

1, a dynamic proxy class is more simple, can solve the problem of creating multiple static agents, to avoid repeated redundant code

2, call the target code, will be in the method "runtime" dynamic join, determine what type you are, only adjust who, flexible


Disadvantages :

1, the system is flexible, but compared to 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 easy to understand

3, 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 in the end what kind of agent, no best, only 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.