Java proxy mode

Source: Internet
Author: User

Java proxy mode

Proxies can be divided into: static proxies (staticproxy) and dynamic proxies (dynamicproxy).

Agent Concept

Provides a proxy for an object to control access to the object. The proxy class and the delegate class have a common parent and parent interface so that proxy objects can be used wherever the delegate class object is used. The proxy class is responsible for the preprocessing of the request, filtering, assigning the request to the delegate class processing, and subsequent processing after the delegate class finishes executing the request. The agent is divided into static agent and dynamic Agent .

Personal feeling agency this model draws on the advantages of inheritance and combination, that is, no sensitive information is exposed to the delegate class, and can be used to achieve more functions by using combination. As for the delegate class and the proxy class to implement a common interface (so-called Proxy interface), the purpose is to let users feel that there is no intermediate proxy class. (as if some intermediary agencies do a very covert, so that users and owners feel no third-party like).

Static proxy

The client in the diagram is the party that invokes the interface, the Proxy interface (Subject), the delegate class (Realsubject), the proxy class (Proxysubject), and communicates with the user through the proxy class. Below with a small story to explain the proxy mode:A June has a set of houses to sell, because the buyer is not good to find directly hanging in the B June's consignment company, after a period of time buyers C-June directly to the House to buy away. look at the following code implementation:

interface sell {public void sellHouse();}class PersonA implements sell{public void sellHouse() {    System.out.println("RealSubject...SellHouse...");}}class PersonB implements sell{//代理君B持有一个真实类(房主A)的实例,可以想象类似成留了一个电话号码,有人来买房子就立马通知PersonA a = new PersonA();public void sellHouse() {    //有人来买房就立马通知真实类(房主A)...    a.sellHouse();    System.out.println("Proxy...SellHouse...");}}public class JavaTest{public static void main(String[] args) {    //我就相当于是买房子的C君    PersonB b = new PersonB();    //我直接找代理B君买房子    b.sellHouse();}}运行结果为:RealSubject...SellHouse...Proxy...SellHouse...

As for the real class and the proxy class need to implement the same interface, Ted that the unified interface allows the client to use the real class object in the place can be replaced by proxy class, without changing the method of its invocation. Because the call class here can not implement the interface at all, using the combined attributes to hold the object of the real class, by customizing several methods to directly invoke the real class method, so that the interface exposed to the outside world is the proxy class to customize some of the interface.

Dynamic Agent

The dynamic agent mechanism introduced in JDK 5 allows developers to dynamically create proxy classes and their objects at run time. At run time, you can dynamically create a proxy class that implements multiple interfaces.

Speaking of dynamic agents, we have to involve the Java.lang.reflect.Proxy class, which is the parent of all dynamic proxy classes generated by the Java dynamic Agent mechanism, which provides a set of static methods to dynamically generate proxy classes and their objects for a set of interfaces.

The object for each proxy class associates an implementation of the Invocationhandler interface that represents the internal processing logic. When a user invokes a method in the interface that the proxy object proxies, the message is passed to the invocationhandler invoke method. In the parameters of the Invoke method, you can get to the proxy object, the object of the method corresponding to the methods, and the actual arguments of the call, and the result of the execution of the invoke method is returned to the caller. This approach is actually an interception of method invocations.

Simply put, the real class does not know who its proxy class is before it runs, and dynamically generates a proxy class and proxies for real classes during run time through reflection. Here is a small story (purely fictitious, children do not bad ...) To assist understanding:A June (real class) immediately to the test, but his strength is not enough, so want to find someone to test (that is, looking for their own proxy class, before finding their own proxy class is who), and then through the B June (equivalent to Invocationhandler, for distribution call request) Introduction, Found a genius (equivalent to dynamically generated proxy class, do not know who) to help the test . The implementation code is as follows:

Interface Exam {public void Findhelp ();} Class PersonA implements Exam{public void Findhelp () {System.out.println ("persona...find...help ...");} /*** This class is equivalent to B June, for a June dynamic creation of proxy class object */class Myinvocationhandler implements Invocationhandler {private Object targetObject;    public Object Newproxyinstance (object o) {//targetobject is the object of the real class, which is equivalent to a-June targetObject = O;            /* Here dynamically for the incoming real object o dynamically created a proxy class, which is what we say genius * Last parameter this refers to the processing call intercept handler */return Proxy.newproxyinstance ( Targetobject.getclass (). getClassLoader (), Targetobject.getclass (). Getinterfaces (), this );} /** * Intercepts the calling method at the time of invocation, and then does the processing of the phase */@Overridepublic object Invoke (Object proxy, Method method, object[] args) throws Throw Able {return Method.invoke (targetObject, args);}}    public class Javatest{public static void Main (string[] args) {PersonA a = new PersonA ();    Myinvocationhandler MiH = new Myinvocationhandler ();    For a-June dynamically generate proxy class Exam E = (Exam) mih.newproxyinstance (a); e.fiNdhelp ();}} 

Java proxy mode

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.