Java proxy mode

Source: Internet
Author: User

Java proxy mode

1. Proxy mode
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 or cannot refer to another object directly, whereas a proxy object can act as an intermediary between the client and the target object.
The proxy mode typically involves three roles:
Abstract role: A common interface for declaring real objects and proxy objects;
Proxy role: The proxy object role contains a reference to the real object, allowing you to manipulate the real object while the proxy object provides the same interface as the real object to replace the real object at any moment. At the same time, the proxy object can attach other actions when performing the real object operation, which is equivalent to encapsulating the real object.
Real role: The real object represented by the proxy role is the object we end up referencing.

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

Abstract roles:

Abstract public class Subject {
Abstract public void request ();
}


Real character: implements the request () method of subject.

public class Realsubject extends Subject {
Public Realsubject () {}

public void request () {
System.out.println ("from real subject.");
}
}


Agent role:

public class Proxysubject extends Subject {
Private Realsubject Realsubject; Attributes with a real role as a proxy role

Public Proxysubject () {}


public void request () {//The method encapsulates the request method of the Real object
Prerequest ();

if (Realsubject = = null) {

Realsubject = new Realsubject ();
}

Realsubject.request (); The request method for performing real objects here

Postrequest ();
}


Client calls:

Subject sub = new Proxysubject ();
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, a real role must correspond to a proxy role, and if a large number of uses would cause the class to swell dramatically, how would you use a proxy if you didn't know the real role beforehand? This problem can be solved by the dynamic proxy class in Java.

2. Dynamic proxy class

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

(1). Interfaceinvocationhandler: Only one method is defined in this interface Object:invoke (Objectobj,method method, object[] args). 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, which mainly includes the following:

Protectedproxy (Invocationhandler H): A constructor that is estimated to be used to assign a value to an internal h.

Static Classgetproxyclass (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.

Static objectnewproxyinstance (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).

The so-called Dynamicproxy 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.

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):

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.");
}

}


Agent 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 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:

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 (); The proxy class is specified here
Invocationhandler ds = new Dynamicsubject (RS);
Class cls = Rs.getclass ();

The following is a one-time build agent
Subject Subject = (Subject) proxy.newproxyinstance (Cls.getclassloader (), Cls.getinterfaces (), DS);
Subject.request ();

}

Program Run Result:
Beforecalling 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.

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.