Java Design Pattern Learning 06--static agent and dynamic proxy __java

Source: Internet
Author: User
Tags reflection static class

Java Design pattern Learning 06--static agent and dynamic proxy

First, the agent mode

Provides an agent for an object to control access to this agent. The proxy class and the delegate class have a common parent or parent interface, so that proxy class object substitution can be used wherever the delegate class object is used. The proxy class is responsible for the preprocessing of the request, filtering, assigning requests to the delegate class processing, and subsequent processing of the request by the delegate class. II. Structure of Agent mode

UML Class Diagram:

The structure of the proxy pattern in the above diagram is: Abstract role: The common interface between real object and proxy object. Agent role: The proxy object role contains a reference to the real object, so that the real object can be manipulated, while 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 attach other actions when performing the real object operation, which is equivalent to encapsulate the real object. Real role: The real object represented by the agent role is the object that we end up referencing.

Depending on the generation time of the proxy class, the agent can be divided into two kinds: static agent and dynamic agent. third, static agent

The source code of the proxy class is created or generated by the programmer, and then the proxy class is compiled. The so-called static is also in the program before the operation of the byte code file, proxy class and the relationship between the delegate class is determined before running.
Sample code:
1. Abstract roles

Public interface Abstractsubject {
     void dosomething ();
}   
1 2 3 4

2. Agent role

public class Proxysubject implements abstractsubject{
     private Abstractsubject real  ;
     Public Proxysubject (Abstractsubject real  ) {
         this.real=real;
    }
     @Override public
     void DoSomething () {

         real.dosomething ();
    }

     public void dootherthing () {

    }
}   
1 2 3 4 5 6 7 8 9 10 11 12 13 14-15 16

3. Real role

public class Realsubject implements abstractsubject{
     @Override public
     void DoSomething () {
        SYSTEM.OUT.PRINTLN ("Real role is used");
    }
   
1 2 3 4 5 6 7

4. Client

public class Client {public
     static void Main (string[]  args) {
        realsubject real = new  realsubject (); 
  
   proxysubject proxy = new  proxysubject (real);
         Proxy.dosomething ();
    }
   

  
1 2 3 4 5 6 7 8

5. Static Agent Advantages and disadvantages

Advantages: The business class only needs to pay attention to the business logic itself, to ensure the reusability of the business class. This is the common advantage of the agent.
Disadvantage: A proxy object of an interface to serve only one type of object, if you want to proxy a lot of methods, it is bound to be for each method are agents, static agent in the program is slightly larger when the size is not competent. If an interface adds a method, all proxy classes need to implement this method in addition to all implementation classes that need to implement this method. Increases the complexity of code maintenance. Four, dynamic agent

The source of the dynamic proxy class is that the program is dynamically generated by the JVM based on reflection and so on during run time, so there is no bytecode file for the proxy class. The relationship between the agent role and the real role is determined when the program is run.
1. First look at the dynamic agent-related Javaapi
①.java.lang.reflect.proxy
This is the parent class of all proxy classes generated by the Java dynamic Proxy mechanism, which provides a set of static methods for generating proxy classes and their objects dynamically for a set of interfaces.
static method for the proxy class:

Method 1: This method is used to get the call processor  
static Invocationhandler Getinvocationhandler (object proxy)  

/method associated with the specified proxy object 2: This method is used to get the class object  
static Class Getproxyclass (ClassLoader loader,class[] interfaces)/method associated with the dynamic proxy class of the specified class loader and a set of interfaces  

3: This method is used to determine whether a specified class object is a dynamic proxy class  
static Boolean Isproxyclass (class CL)    


//Method 4: This method is used to generate a dynamic proxy class instance for a specified class loader, a set of interfaces, and a calling processor
static Object newproxyinstance (ClassLoader loader,  class[] interfaces, Invocationhandler  h)   
1 2 3 4 5 6 7 8 9 10 11 12-13

②.java.lang.reflect.invocationhandler
This is the calling processor interface, which customizes an invoke method that centralizes the method invocation on the dynamic proxy class object, typically implementing proxy access to the delegate class in the method. Each time a dynamic proxy class object is generated, a corresponding call processor object is specified.
Invocationhandler Core Approach

This method is responsible for centralizing all method calls on the dynamic proxy class. The first parameter is both a proxy class instance and the second parameter is the invoked method object  
//The third method is the invocation parameter. The calling processor is preprocessed based on these three parameters or assigned to a delegate class instance reflection execution   
object Invoke (Object proxy, Method  method,object[] args)     
1 2 3

③.java.lang.reflect.classloader
This is the class loader class, which is responsible for loading the bytecode of the class into the Java virtual machine (JVM) and defining the class object for it, and then the class can be used. Proxy static methods generate dynamic proxy classes also need to be loaded through the class loader to be used, and the only difference between them and the normal class is that its bytecode is generated dynamically by the JVM at runtime rather than in any of the. class files. You need to specify a class loader object each time you generate a dynamic proxy class object.

2. The dynamic proxy implementation step implements the Invocationhandler interface to create its own call processor. Provides the proxy class with an array of ClassLoader and proxy interface types to create dynamic proxy classes. Perform real-world role specific tasks.

Sample code

1. Abstract roles and real character codes are the same as above.
2. Create your own call Processor:

public class Subjecthandler implements invocationhandler{
    abstractsubject Real;
    Public Subjecthandler (Abstractsubject real) {
        this.real=real;
    }

    @Override public
    Object Invoke (Object obj, method method, object[] args) throws Throwable {
        System.out.println (" Proxy class preprocessing task ");
        The reflection mechanism is used to assign the request to the delegate class processing. Method's Invoke returns the object as the result of the methods.  
  //Because the sample program does not return a value, this ignores the return value processing
        method.invoke (real, args);
        SYSTEM.OUT.PRINTLN ("Agent-type follow-up task");
        return null;
    }

}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17-18

3. Client:

public class Client {public

    static void Main (string[] args) {
        realsubject real=new realsubject ();
        Subjecthandler handler=new Subjecthandler (real);
        Generate proxy class object
        abstractsubject proxy= (abstractsubject) proxy.newproxyinstance (Classloader.getsystemclassloader (), New Class[]{abstractsubject.class},handler);
        Proxy.dosomething ();

    }

1 2 3 4 5 6 7 8 9 10 11-12

4. The advantages and disadvantages of dynamic agents

Advantages:
The greatest benefit of dynamic proxies compared to static proxies is that all of the methods declared in the interface are transferred to the calling processor in a centralized method (Invocationhandler.invoke). In this way, when the number of interface methods is much higher, we can deal with flexibly, without needing to relay every method like static proxy.

Insufficient:
Admittedly, Proxy has been beautifully designed, but there is a little bit of regret that it has never been able to get rid of the shackles that support the interface agent because its design is doomed to this regret. Recall the inherited graphs of dynamically generated proxy classes, which are already destined to have a common parent called proxy. The Java inheritance mechanism has doomed these dynamic proxy classes to be unable to implement dynamic proxies for class, because multiple inheritance is inherently impractical in Java.

This dynamic proxy portion of this article is heavily quoted: http://layznet.iteye.com/blog/1182924

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.