Design mode--proxy mode

Source: Internet
Author: User

Introduction of Agent 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 .

There are two main types of proxy modes: static agents and dynamic proxies

second, static agent 1. The role that the proxy model typically involves

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.

2. Reference Code1) Abstract Roles

public abstract class Abstractsubject {
    public abstract void request ();
}

< Span style= "color: #ff0000;" >2 " real role

public class Realabstract extends abstractsubject{
    public void request () {
        system.out.println ("from Real Subject! ");         
    }
}

3) Agent Role

public class Proxysubject extends abstractsubject{
The proxy Role object contains a reference to the real object inside
Private Realabstract realabstract;
public void request () {
Actions that are attached before a real role operation
Prerequest ();
if (null = = Realabstract)
{
Realabstract = new Realabstract ();
}
What real characters do.
Realabstract.request ();
Actions that are attached after a real role operation
Postrequest ();
}
private void Prerequest () {
System.out.println ("Pre Request.");
}
private void Postrequest () {
System.out.println ("Post Request");
}
}

4) Test class

public class Client {
public static void Main (string[] args) {
Abstractsubject subject = new Proxysubject ();
Subject.request ();
}
}

Questions:

If you want to use proxy mode in the way described above (static proxy), then the real role must be the implementation already exists and as the internal property of the proxy object.

But when actually used, a real role must correspond to a proxy role, but if a large number of uses can lead to the rapid expansion of the class, in addition, if you do not know the real role, how to use the proxy? This problem can be solved by the dynamic proxy class in Java.

Second, dynamic agent

Dynamic Agent Dynamic Proxy is the method by which a customer invokes other objects through a proxy class. Dynamic proxy usage Scenarios: debug, Remote method Invocation (RMI).

1. Classes covered by dynamic agents

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 is defined in the interface:

  Object Invoke (Object proxy, 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, request (), args is the parameter array for the method (NULL when no parameter is set).

This abstract method is implemented dynamically in the proxy class.

  2. Proxy

The class is a dynamic proxy class that acts like the proxysubject in the example above, which mainly includes the following:

  Protected Proxy (Invocationhandler H): constructor, used to assign values to internal invocation handler.

  Static class<?> Getproxyclass (ClassLoader loader, class<?> .... Interfaces): Loader is a class loader, 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 the method declared by the proxy class in the subject interface).

  3. Dynamic proxy class Description

The so-called dynamic Proxy is a class:

It is the class generated at runtime and you must 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. Each dynamic proxy class will have a invocation handler associated with it. The real call is done in the Invoke () method of the invocation handler.

2. Dynamic Agent Steps

1) Create a class that implements the interface Invocationhandler, which must implement the Invoke () method.

2) Create the class and interface to be proxied.

3) Create a proxy through the static method of proxy newproxyinstance (ClassLoader loader, class<?>[] interfaces, Invocationhandler h).

4) The method is called through the proxy.

3.Dynamic Proxy Reference Code

1) Abstract Roles

Public abstract class Abstractsubject {
public abstract void request ();
}

2) Real characters

public class Realabstract extends abstractsubject{
public void request () {
System.out.println ("from Real subject!");
}
}

3) Create a class that implements the interface Invocationhandler

Import Java.lang.reflect.InvocationHandler;
Import Java.lang.reflect.Method;

public class Dynamicsubject implements Invocationhandler {
   // References to real objects
    Private Object sub;
    public dynamicsubject (Object obj) {
        this.sub = obj;
        
   }
    public Object Invoke ( Object Proxy, method, object[] args
            throws throwable {
        system.out.println ("before calling:" + method);        
       //Invoke method by reflection
         Method.invoke (Sub, args);       
         System.out.println ("after calling:" + method);
        return null;
    }
}

< Span style= "color: #ff0000;" >

import Java.lang.reflect.InvocationHandler;
Import Java.lang.reflect.Proxy;

public class Client {
    public static void Main (string[] args) {
         realabstract realsubject = new Realabstract ();
        Invocationhandler handler = new Dynamicsubject (realsubject);
        class<?> ClassType = Handler.getclass ();
       //Generation Agent
       // Dynamically generates a class (implements the specified interface), generates an object of the class, translates to interface type
        abstractsubject subject = ( Abstractsubject) proxy.newproxyinstance (

Classtype.getclassloader (),

Realsubject.getclass (). Getinterfaces (),
                 handler);
        subject.request ();
       //Call method, transfer to Handler takeover, by which the Invoke () method actually completes the method execution
         System.out.println (Subject.getclass ());//Print out: Class $Proxy 0
        //$Proxy 0 is a class that is dynamically generated during run
    }

}

 In this way, the Proxied object (Realsubject) can be dynamically changed at runtime, the interface to be controlled (Abstractsubject interface) can be changed at run time, the control mode (Dynamicsubject Class) can also be changed dynamically, Thus, a very flexible dynamic agent relationship is realized.

Design mode--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.