Java proxy mode

Source: Internet
Author: User
Tags object object throwable

Introduction

When we write a functional function, we often write code that is not function-independent, such as logging, parameter checking, security, and transaction support. The function-independent code is mixed in the function, which brings some trouble

    • Damage to Oo
    • Deepen the coupling between classes
    • Reduced code Reuse

The proxy mode solves this problem, and the key function code is placed in the function, and the side code is placed in the proxy class.

Proxy Mode

2. Use

The role of proxy mode is to provide a proxy for other objects, without changing the interface, to control access to the object

2. Role

Proxy mode typically involves 3 roles: abstract Role (interface), proxy role, Real ( proxied) role

3. Type

Static agent, dynamic agent (JDK agent, cglib agent)

Static proxy

The proxy class, the proxy class need to implement the same interface, or inherit the same parent class

/*** Created by Danny.yao on 2017/10/9. * In static proxies, the proxy class and the proxy class need to implement this interface*/ Public InterfaceIuser { Public voiddosomething (String thingstodo);} /*** Created by Danny.yao on 2017/10/9. * Proxy class, Real business logic*/ Public classDannyImplementsIuser { Public voiddosomething (String thingstodo) {System.out.println ( This. GetClass (). GetName () + "sing one side" +Thingstodo); }} /*** Created by Danny.yao on 2017/10/9. * Proxy class, the proxy class as its properties, enhanced by the proxy class function*/ Public classUserproxyImplementsIuser {PrivateIuser User;  Publicuserproxy (iuser user) { This. user =user; }    //enhance functionality without changing the behavior of Danny     Public voiddosomething (String thingstodo) {dobefore ();        User.dosomething (Thingstodo);    Doafter (); }    Private voidDobefore () {System.out.println ("The room was very ..." "); System.out.println ("Get up and wash up ..." "); System.out.println ("Breakfast ..." "); System.out.println ("Then ... "); }    Private voidDoafter () {System.out.println ("After that what ... "); System.out.println ("Start playing King glory!" "); }}

Test class

 Public class userproxytest {    @Test    publicvoid  testdosomething () {        new Userproxy (new  Danny ());        Dannyproxy.dosomething ("Work!! ");    }}

Disadvantages:

    • The proxy class must already exist, and as an internal property of the proxy class
    • Each business class needs a proxy class, and if the volume of business is large, it can cause the class to swell sharply.
Dynamic Agent

The source code of the dynamic proxy class is dynamically generated by the JVM based on the mechanism of reflection during the program running.

1. JDK Agent

The proxy class, must implement the interface; proxy class, do not need to implement interface

//interfaces and implementation classes, with static proxies  Public classDynamicproxyImplementsInvocationhandler {//to change a class reference in a static proxy to an object type    PrivateObject object;  PublicDynamicproxy (Object object) { This. Object =object; }    //to change the method call process to reflection mode, independent of the interface specific method     PublicObject Invoke (Object proxy, Method method, object[] args)throwsthrowable {dobefore ();        Method.invoke (object, args);        Doafter (); return NULL; }    Private voidDobefore () {System.out.println ("Before that what ... "); }    Private voidDoafter () {System.out.println ("After that what ... "); }    //back to Dynamic agent Newproxyinstance (ClassLoader loader, class<?>[] interfaces, Invocationhandler h)     Public<T>T GetProxy () {return(T) proxy.newproxyinstance (Object.getclass (). getClassLoader (), Object.getclass (). Getinte Rfaces (), This        ); }}

Test class

 Public class dynamicproxytest {    @Test    publicvoidthrows  Exception {         New Dynamicproxy (new  Danny ());         = dynamicproxy.getproxy ();        Dannyproxy.dosomething ("Work!! ");    }}

Disadvantages:

    • An interface must be implemented by the proxy class
2, cglib agent

Also known as a subclass proxy, it is to build a subclass object in memory, thus extending the functionality of the target object. The proxy class does not need to implement an interface

//classes that do not implement an interface Public classPig { Public voiddosomething (String thingstodo) {System.out.println ("Lazy" +Thingstodo); }}  Public classCglibproxyImplementsMethodinterceptor { PublicObject Intercept (Object o, method, object[] args, Methodproxy methodproxy)throwsthrowable {dobefore (); Object result=methodproxy.invokesuper (o, args);        Doafter (); returnresult; }    //Cglib to create an agent through a reinforcing device     Public<T> T GetProxy (class<t>Tclass) {        return(T) enhancer.create (Tclass, This); }    Private voidDobefore () {System.out.println ("Before that what ... "); }    Private voidDoafter () {System.out.println ("After that what ... "); }}

Test class

 Public class cglibproxytest {    @Test    publicvoidthrows  Exception {         New cglibproxy ();         = Cglibproxy.getproxy (Pig.  Class);        Pigproxy.dosomething ("thinking about life ... ");    }}

Disadvantages:

    • All methods of the proxy class are intercepted and packaged, without the method-level personalization interception

Reference:

https://www.zhihu.com/question/20794107

Http://www.cnblogs.com/machine/archive/2013/02/21/2921345.html

Http://www.cnblogs.com/cenyu/p/6289209.html

Java proxy mode

Related Article

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.