Java Proxy mechanism

Source: Internet
Author: User

1 Introduction

When we write a function that performs a function, it is often necessary to write code that is not directly related to the function but is necessary, such as logging, information sending, security, and transaction support, which are necessary, but it brings the following problems:

    1. The irrelevant code is free from the functional code, it is the purpose of the function, which is a kind of destruction to Oo
    2. The side-by-side code causes the functional code to rely on other classes, deepening the coupling between classes, which the OO system is trying to avoid.
    3. The coupling degree caused by the minor code can cause the portability of the functional code, and the reusability is reduced.
    4. In jurisprudential terms, the minor code should ' monitor ' the functional code and then take action instead of the functional code ' notice ' that the minor Code takes action, which is like the Bard should be active in documenting the Knight's merit rather than the Knight asking the poet to record his merits.
2 Common proxies

There is no doubt that the side code and functional code need to be separated to reduce the degree of coupling, in line with the requirements of modern OO systems, we can use the proxy mode to complete this requirement.

The role of proxy mode is to provide a proxy for other objects to control access to this object. In some cases, one customer does not want to refer directly to another object, whereas a proxy object can mediate between the client and the target object. The proxy mode typically involves three roles:

    1. Abstract role: Common interface for declaring real objects and proxy objects
    2. Proxy role: The proxy object contains a reference to the real role, so that the real role can be manipulated, while the proxy object and the real object has the same interface, can at any time replace the real object, while the proxy object can execute the real object before and after the implementation of the specific logic to achieve the extension of the function.
    3. Real role: The real object represented by the proxy role, which is the object we end up referencing

The common agents are:

    1. Remote proxy: Provides a local representative object for a different address space object, such as stubs in RMI
    2. Virtual Proxy: A resource that consumes large or complex objects as needed, delays loading, and creates only when it is really needed
    3. Protection agent (Protect or Access Proxy): Controls access to an object.
    4. Smart Reference (Smart Reference Proxy): Provides additional services and functionality than the target object.

Through the middle layer of proxy class, it can effectively control the direct access to the actual delegate class object, but also hide and protect the actual object, implement different control strategies, and gain more flexibility in design.

3 proxy mode UML diagram

A proxy is a common design pattern designed to provide a proxy for other objects to control access to an object. The proxy class is responsible for preprocessing the message for the delegate class, filtering the message and forwarding the message, and subsequent processing after the message is delegated to the class.

4 Proxy Mode instance

Here's an example of the examples in Java and patterns:

//Abstract roles:AbstractPublicClassSubject {AbstractPublicvoidRequest ();}//Real character: Implement the request () method of subjectPublicClassRealsubjectExtendsSubject {Public Realsubject () {}PublicvoidRequest () {SYSTEM.OUT.PRINTLN ("From real subject."); }}//Agent role:PublicClassProxysubjectExtendsSubject {//Attributes with a real role as a proxy rolePrivateSubjectRealsubject;Public Proxysubject (subject realsubject) { This.realsubject = realsubject} // This method encapsulates the request method of the real object public void request () {prerequest (); Realsubject.request (); // Here Execute the request method of the Real object Postrequest ();} ...} // client invoke: RealSubject real = new realsubject (); subject sub = new  Proxysubject (real); Sub.request ();                

As can be seen from the above code, the customer actually needs to call the Realsubject class request () method, now use Proxysubject to proxy the Realsubject class, also to achieve the purpose, but also encapsulates the other methods (Prerequest (), Postrequest ()), you can handle some other issues.

In addition, if you want to use the proxy mode as described above, the real role must be pre-existing and used as the internal property of the proxy object. But when used in practice, if a proxy is to be applied to a real role, each real object must correspond to a proxy role, and if a large number of uses will cause a sharp expansion of the class, and if you do not know the real role beforehand, how do you use the proxy class? This problem can be solved by the dynamic proxy class in Java.

5 Java Dynamic Agent

The so-called dynamic Proxy is a class that is generated at runtime and you have to provide a set of interface to it when it is generated, and then the class declares that it implements these interface. You can certainly use this class instance as any of these interface. Of course, this dynamic proxy is actually a proxy, it will not do a substantial job for you, in the generation of its instance you must provide a handler, it takes over the actual work.

5.1 java Dynamic proxy UML diagram

The Java dynamic proxy class is located under the Java.lang.reflect package, which generally involves the following two classes:

    1. Interface Invocationhandler: Only one method Object:invoke (Object Obj,method method, object[] args) is defined in this interface. When actually used, the first parameter, obj, generally refers to the proxy class, which method is the proxy, as in the previous example, the request (), args is the parameter array for the method. This abstract method is implemented dynamically in the proxy class.
    2. Proxy: This class is a dynamic proxy class that acts like the proxysubject in the previous example.
    3. Protected Proxy (Invocationhandler H): constructor, estimated to be used to assign values to internal H.
    4. Static class Getproxyclass (ClassLoader loader, class[] interfaces): Gets a proxy class, where loader is a class loader, and interfaces is an array of all the interfaces owned by the real class.
    5. Static Object newproxyinstance (ClassLoader loader, class[] interfaces, Invocationhandler h): Returns an instance of the proxy class, The returned proxy class can be used as a proxy class (you can use a method declared in the subject interface of the proxy class).

When using dynamic proxy classes, we must implement the Invocationhandler interface with the example in the first section:

//Abstract role (previously an abstract class, which should be changed to an interface here):PublicInterfaceSubject {AbstractPublicvoidRequest ();}//Specific role Realsubject:PublicClassRealsubjectImplementsSubject {Public Realsubject () {}PublicvoidRequest () {SYSTEM.OUT.PRINTLN ("From real subject."); }}//Agent Processor:ImportJava.Lang.Reflect.Method;ImportJava.Lang.Reflect.Invocationhandler;PublicClassDynamicsubjectImplementsInvocationhandler {PrivateObjectsub; public Dynamicsubject () {} public dynamicsubject (object obj) {sub = obj;} public object invoke (object proxy, method method, object[] args) Span class= "Org-keyword" >throws throwable {System.out.println ( " Before calling "+ method); Method.invoke (Sub,args); System.out.println ( "after calling" + method); return null;}        

The internal property of the proxy class is the object class, which is actually assigned by the constructor of the class Dynamicsubject (object obj), and in addition, the Invoke method is implemented in the class, and the

Method.invoke (Sub,args);

In fact, it is the method that invokes the object being executed, the method parameter sub is the actual proxy object, and args is the parameter required to perform the corresponding operation of the Proxied object. With dynamic proxy classes, we can perform some related operations before or after the call.

//Client:ImportJava.Lang.Reflect.Invocationhandler;ImportJava.Lang.Reflect.Proxy;ImportJava.Lang.Reflect.Constructor;ImportJava.Lang.Reflect.Method;PublicClassClient {StaticPublicvoidMainString[]ArgsThrowsThrowable {Realsubjectrs =NewRealsubject ();//The proxy class is specified hereInvocationhandlerds = new DynamicSubject (RS); Span class= "Org-type" >class cls = Rs.getclass (); // The following is a one-time generation agent Subject subject = (subject) proxy.newproxyinstance (Cls.getClassLoader (), Cls.getinterfaces (), DS); Subject.request (); }}// program run Result: Before calling public abstract void Subject.request () from real Subject.after calling public abstract void subject.request ()       

In this way, the Proxied object (Realsubject) can be dynamically changed at runtime, the interface that needs to be controlled (subject interface) can be changed at runtime, the control mode (Dynamicsubject Class) can also be changed dynamically, thus realizing a very flexible dynamic agent relationship.

6 The difference between agent mode and decorator mode

The proxy mode is much like the decorator pattern, in typical cases, such as spring's AOP, the remote proxy class, and the JDK proxy, are all agent modes. The input/output device in the JDK is a typical decorator mode! But in some scenarios, the beginner of the design pattern is still a bit difficult to distinguish, UML class diagram Basically no difference, is to implement the same interface, one class wrapper another class. The definition of both:

    • Adorner mode: The behavior of new or combined objects that can be dynamically added
    • Proxy mode: Provides a proxy for other objects to control access to this object

The adornment mode is "new behavior", while the proxy mode is "Control access". The key is how we judge whether "new behavior" or "Control access". You write the decorations in one place, and everyone knows that it is in addition to the function that you write the agent that everyone knows is in the limit.

6.1 Decorator mode UML diagram

The duties of the classes are as follows:

    1. Abstract component Role (Project): An interface is given to standardize the objects that are ready to receive additional responsibilities
    2. Concrete component Role (Employe): Defines a class that will receive additional responsibilities
    3. Decorative Role (Manager): Holds an instance of a Component object and defines an interface that is consistent with the abstract component interface
    4. Specific decorative roles (Managera, Managerb): Responsible for "attaching" additional responsibilities to the component objects
6.2 image Description

Proxy mode: Controls the access of the object without changing the interface

Example: Monkey King plays and replaces the high family three miss

Monkey King played Miss Gaojiasan, so it can be said that the Sun Wukong and Miss Gaojiasan have a common interface. If pig only want to see the had bloomed face of the high family, or talk about the sky, then the three Miss "Agent" Monkey King is allowed, but pig want to kiss the mouth, then it is not possible. This is an application that protects the proxy mode. The client's request is passed to the real subject object only if the proxy object is considered appropriate.

Decorative mode: Dynamically extending the function of an object without changing the interface

Sun Wukong has 72 changes, in the eyes of the two lang God, he will always be the Hozen. Decorating mode dynamically attaches more responsibility to an object in a transparent manner to the customer. In other words, the client does not feel that the object is different before and after decorating. Adornment mode expands the functionality of an object without using the creation of more subclasses. Each of his changes brought him an additional skill. When he became a fish, he could swim in the water, and when he became a sparrow, he could fly in the sky. And not Takui how to change, in the eyes of the two lang God, he will always be the Hozen. Decorating mode dynamically attaches more responsibility to an object in a transparent manner to the customer. In other words, the client does not feel that the object is different before and after decorating. Adornment mode expands the functionality of an object without using the creation of more subclasses.

Java Proxy mechanism

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.