Java design mode (1) -- proxy mode and dynamic proxy class

Source: Internet
Author: User

The proxy mode provides a proxy for other objects to control access to this object. In some cases, a client does not want or cannot directly reference another object, and the proxy object can play a mediation role between the client and the target object.

The proxy mode generally involves the following roles:

Abstract role: Declares the common interfaces of real objects and proxy objects;

Proxy role: the proxy object role contains a reference to the real object to operate on the real object. At the same time, the proxy object provides the same interface as the real object to replace the real object at any time. At the same time, the proxy object can append other operations when performing real object operations, which is equivalent to encapsulating real objects.

Real role: the real object represented by the proxy role is the object we finally want to reference.

Applicable environment: it is applicable when you need to obtain initialized objects and there is no specific way to obtain them.

The following example uses Java and mode:

Abstract role:
Java code
Abstract public class Subject {
Abstract public void request ();
}
Real role: implements the Subject request () method.
Public class RealSubject extends Subject {
Public RealSubject (){}

Public void request (){
System. out. println ("From real subject .");
}
}


Proxy role:
Public class ProxySubject extends Subject {
Private RealSubject realSubject; // attributes of a real role as a proxy role

Public ProxySubject (){}


Public void request () {// This method encapsulates the request Method of the real object
PreRequest ();

If (realSubject = null ){

RealSubject = new RealSubject ();
}

RealSubject. request (); // The request Method of the real object is executed here.

PostRequest ();
}


Client call:
Subject sub = new ProxySubject ();
Sub. request ();

From the above code, we can see that the customer actually needs to call the request () method of the RealSubject class, And now uses ProxySubject to proxy the RealSubject class, which achieves the same purpose, other methods (preRequest () and postRequest () are encapsulated to handle other problems.

In addition, if you want to use the proxy mode according to the preceding method, the real role must exist in advance and act as the internal attribute of the proxy object. However, in actual use, a real role must correspond to a proxy role. If a large number of roles are used, the class will expand sharply. In addition, if you do not know the real role, how can you use the proxy? This problem can be solved through the dynamic proxy class of Java.
 
2. Dynamic proxy

The Java Dynamic proxy class is located under the Java. lang. reflect package and generally involves the following two classes:

(1). Interface InvocationHandler: this Interface defines only one Method Object: invoke (Object obj, method Method, Object [] args ). In actual use, the first parameter obj generally refers to the proxy class, and the method is the method to be proxy. In the preceding example, request () and args are the parameter arrays of this method. This abstract method is dynamically implemented in the proxy class.


(2). Proxy: this class is a dynamic Proxy class, which is similar to ProxySubject in the previous example. It mainly includes the following content:

Protected Proxy (InvocationHandler h): constructor, which is used to assign values to the internal h.

Static Class getProxyClass (ClassLoader loader, Class [] interfaces): obtains a proxy Class. loader is the Class loader, and interfaces is the array of all interfaces of the real Class.

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 (the method declared in the Subject interface of the proxy class can be used ).

 

Dynamic Proxy is a class that is generated at runtime. You must provide a set of interfaces to it when generating it, then the class declares that it implements these interfaces. Of course, you can use the class instance as any of these interfaces. Of course, this Dynamic Proxy is actually a Proxy, and it will not do substantial work for you. When generating its instance, you must provide a handler to take over the actual work.

When using a dynamic proxy class, we must implement the InvocationHandler interface. Take the example in Section 1 as an example:


Abstract role (previously an abstract class, which should be changed to an interface here ):

Public interface Subject {
Abstract public void request ();
}

 

Specific role RealSubject:
Public class RealSubject implements Subject {

Public RealSubject (){}

Public void request (){
System. out. println ("From real subject .");
}

}


Proxy processor:
Import java. lang. reflect. Method;

Import java. lang. reflect. InvocationHandler;

Public class DynamicSubject implements InvocationHandler {
Private Object sub;
Public DynamicSubject (){}

Public DynamicSubject (Object obj ){
Sub = obj;
}

Public Object invoke (Object proxy, Method method, Object [] args) throws Throwable {
System. out. println ("before calling" + method );
Method. invoke (sub, args );

System. out. println ("after calling" + method );
Return null;
}

}

 

The internal attribute of the proxy class is the Object class. In actual use, the class's constructor DynamicSubject (Object obj) is used to assign values to it. In addition, the invoke method is also implemented in this class.

Method. invoke (sub, args );

Actually, it is to call the method to be executed by the proxy object. The method parameter sub is the actual proxy object, and args is the parameter required to execute the corresponding operation of the proxy object. Through the dynamic proxy class, we can execute some related operations before or after the call.

Client:

Import java. lang. reflect. InvocationHandler;
Import java. lang. reflect. Proxy;
Import java. lang. reflect. Constructor;
Import java. lang. reflect. Method;

Public class Client {

Static public void main (String [] args) throws Throwable {

RealSubject rs = new RealSubject (); // specifies the proxy class here
InvocationHandler ds = new DynamicSubject (rs );
Class cls = rs. getClass ();

// The following is a one-time generation Proxy:
Subject subject = (Subject) Proxy. newProxyInstance (cls. getClassLoader (), cls. getInterfaces (), ds );
Subject. request ();

}

Author "l12052124"
 

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.