JAVA Agent mode (proxy)

Source: Internet
Author: User

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 agent model generally involves the following 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 inJava and Patterns:

Code:

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 ();
}
private void Prerequest () {
Something want to do before requesting
}
private void Postrequest () {
Something you want to does after requesting
}
}

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 Agent

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, which mainly includes the following:
Protected Proxy (Invocationhandler H): constructor, estimated to be used to assign values to internal H.

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.

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

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. (See document 3)

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

Code:

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

public interface subject{
public void request ();
}

Specific role Realsubject: implements the request () method of the subject interface.
public class Realsubject implements subject{
Public Realsubject () {

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

Agent role:
Import Java.lang.reflect.Method;
Import Java.lang.reflect.InvocationHandler;
public class Dynamicsubject implements invocationhandler{
Private Object Sub;
Public Dynamicsubject (Object sub) {
This.sub = Sub;
}
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 sub), and in addition, the Invoke method is implemented in the class, and the "Method.invoke (Sub,args) in the method "In fact, is to invoke the proxy object will be executed method, the method parameter sub is the actual proxy object, args for the execution of the proxy object corresponding operation required parameters." With dynamic proxy classes, we can perform some related operations before or after the call.

Client:
Code:

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 (); Here you specify the proxy class
  invocationhandler ds = new Dynamicsubject (RS);//Initialize proxy class
  class CLS = Rs.getclass ();
  //The following is the decomposition step
  /*
  class c = Proxy.getproxyclass (Cls.getclassloader (), Cls.getinterfaces ());
  constructor ct=c.getconstructor (New Class[]{invocationhandler.class});
  subject Subject = (Subject) ct.newinstance (New Object[]{ds});
*/

//The following is a one-time build

  subject Subject = (Subject) proxy.newproxyinstance (Cls.getclassloader ( ), Cls.getinterfaces (), DS);
  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.

----------------

The difference between static agent and dynamic agent

Pending additions

3. Proxy mode usage reasons and application aspects

(1) Authorization mechanism different levels of users have different access rights to the same object, such as the Jive Forum system, the use of proxy for authorization mechanism control, access to the forum there are two kinds of people: Registered users and visitors (unregistered users), In Jive, a proxy such as Forumproxy is in control of both users ' access to the forum.

(2) A client cannot directly manipulate an object, but must interact with that object.
Examples of two specific cases:
If the object is a large picture, it takes a long time to display, then when the picture is included in the document, use the editor or browser to open the document, open the document must be very fast, cannot wait for the big picture processing to complete, then need to do a picture proxy to replace the real picture.

If the object is on a remote server on the Internet and the object is directly manipulated because the network speed may be slow, then we can replace that object with proxy first.

The principle is that for a very expensive object to be created only when it is used, this principle can save us a lot of valuable Java memory. So, some people think that Java consumes resource memory, I think this and programming ideas also have a certain relationship.

(3) In reality, the application scope of proxy is very wide, and now the popular distribution method RMI and CORBA are the application of proxy mode.

JAVA Agent mode (proxy)

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.