Agent Mode and Agent Mode

Source: Internet
Author: User

Agent Mode and Agent Mode

In java design patterns, a design pattern is very important, namely the proxy pattern. The proxy pattern generally involves the role

Abstract role: Declares the real object and proxy objectCommon interface.

Real role: the final object to be accessed by the user, which is the real object represented by the proxy role.

Proxy role: You can access a real role through the proxy role. The proxy role contains a reference of a real role. You can use this reference to operate on real objects, at the same time, the proxy object provides the same interface as the real object so that it can replace the real object at any time,The proxy object can be appended with other operations when performing real object operations, Which is equivalent to adding additional functions to implement the functions of real objects.

Proxy roles can be seen everywhere in life. proxy roles can be used to separate customers from real roles, as if students are looking for part-time jobs in their lives and need to seek them through an intermediary, what really offers a job is not an intermediary, but a company where you work part-time. The intermediary is equivalent to an agent role. If you are a Customer looking for part-time jobs, your part-time Company is a real role.

The following is an example of a simple static proxy.

1 package proxy; 2 // defined abstract class. Both the proxy role and the real role must inherit from it. 3 public abstract class Subject4 {5 public abstract void output (); 6}Subject1 package proxy; 2 // real role, implement the Subject abstract class function 3 public class RealSubject extends Subject4 {5 public void output () 6 {7 System. out. println ("from real subject"); 8} 9}RealSubject 1 package proxy; 2 // proxy role 3 public class ProxySubject extends Subject 4 {5 private RealSubject realSubject; // References containing real roles 6 7 @ Override 8 public void output () 9 {10 this. preOutput (); // method executed before calling the method of the real role 11 if (null = realSubject) 12 {13 realSubject = new RealSubject (); 14} 15 realSubject. output (); // call the method of the real role 16 this. postOutput (); // Method 17} 18 19 public void preOutput () 20 {21 System. out. println ("pre output"); 22} 23 public void postOutput () 24 {25 System. out. println ("post output"); 26} 27}ProxySubject 1 package proxy; 2 // Client 3 public class Client 4 {5 public static void main (String [] args) 6 {7 Subject subject = new ProxySubject (); // generate proxy instance 8 subject. output (); // Method for calling a real role 9} 10}Client

The proxy role enables each role to complete its own functions. The real role is associated with the customer through the proxy role, but this proxy mode has its disadvantages, that is, a real role must exist in advance and act as the internal attribute of the proxy object. However, in actual applications, a real role must correspond to a proxy role, that is to say, each time you define a real role, you need to define a proxy role. If you use a large number of roles, the class will increase dramatically. In addition, if you do not know the real role beforehand, you cannot use the proxy. However, this problem can be solved through the dynamic proxy of java.

The dynamic proxy class is also located under the java. lang. reflect package, mainly involving the following two classes

1. Interface InvocationHandler: this Interface defines only one public object invoke (Object obj, Method method, Object [] args). In actual use, the first parameter generally refers to the proxy class, method is the proxy method, and args is the parameter array of the method. This abstract method is dynamically implemented in the proxy class. Each proxy instance is associated with an InvocationHandler, which is written in jdk.

2. Proxy: this class is a dynamic Proxy class. If it is used, it is similar to ProxySubject. The main content is

1) protected Proxy (InvocationHandler h): constructor used to assign values to internal h.
2) 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.
3) staticObjectnewProxyInstance (ClassLoaderloader, Class [] interfaces, InvocationHandlerh) returns an instance of the proxy Class. The returned proxy Class can be used as the proxy Class (the method of the Subject interface of the proxy Class can be used)

A dynamic proxy is used to generate a class at runtime and provide it with a set of interfaces. You can implement any interface, to generate a dynamic proxy instance, you must provide a handler (which implements the InvocationHandler Interface) to take over the actual work. Therefore, when using a dynamic proxy class, you must implement the InvocationHandler interface. To create a dynamic proxy, follow these steps:

1. Create a proxy class and an interface

2. Create a class that implements the InvocationHandler interface and implement the invoke method.

3. Use the static Proxy method newProxyInstance (ClassLoader loader, Class [] interfaces, InvocationHandler handler) to create a Proxy

4. Call the method through the created proxy

The following example shows how to create a dynamic proxy.

1 package dynamicProxy; 2 // define the interface to be implemented by the proxy class 3 public interface Subject {4 public void output (String str); 5 6}Subject1 package dynamicProxy; 2 // real object implementing the Interface 3 public class RealSubject implements Subject {4 public void output (String str) 5 {6 System. out. println (str + "from real"); 7} 8}RealSubject 1 package dynamicProxy; 2 // This class implements the InvocationHandler interface and overwrites the invoke method 3 import java. lang. reflect. invocationHandler; 4 import java. lang. reflect. method; 5 6 public class DynamicSubject implements InvocationHandler {7 private Object object = new Object (); // you can use an Object to transmit any class 8 public DynamicSubject (Object obj) to be proxies) 9 {10 this. object = obj; 11} 12 13 @ Override14 public Object invoke (Object proxy, Method method, Object [] args) 15 throws Throwable {16 System. out. println (method); 17 method. invoke (object, args); // equivalent to the output method of realsubject, the object is the real object to be proxy, and The args is the 18 return null parameter to be passed; 19} 20 21}DynamicSubject 1 package dynamicProxy; 2 3 import java. lang. reflect. invocationHandler; 4 import java. lang. reflect. proxy; 5 6 public class Client {7 public static void main (String [] args) {8 9 Subject sub = new RealSubject (); 10 InvocationHandler handler = new DynamicSubject (sub ); 11 12 Class <?> ClassType = handler. getClass (); 13 // generate a proxy and call the method to InvocationHandler. The subject class generated here declares that sub is implemented. getClass (). all interfaces of getInterfaces 14 Subject subject = (Subject) Proxy. newProxyInstance (classType. getClassLoader (), sub. getClass (). getInterfaces (), handler); 15 subject. output ("CIACs"); // PASS Parameters and methods to the invoke16 17 System of DynamicSubject. out. println (subject. getClass (). getName (); // print the output and dynamically generate the proxy class name 18} 19}Client

Output result:

Dynamic proxy is available for debugging and remote method calls. The customer calls real object methods through the proxy class. A proxy class can generate many proxy instances, achieving one-to-many effects.


Java proxy Mode

This is not like the real proxy mode, right?
The image is simulated.
Net is the Proxy object and calls net. when browse is used, the net check method is called to perform some inspection and other work, and then the browse method of the delegate object is called for real business processing. In fact, the method specified by the delegate object is always executed.
The Proxy class is mainly for the delegate class to pre-process messages, filter messages, and transfer messages to the delegate class and post-processing. The Proxy class does not really implement the service
The Proxy class and InvocationHandler interface provided by Java provide dynamic Proxy class generation
For details, you can refer to the classes and interfaces under java. lang. reflect. In fact, the reflection mechanism of java is mainly used, which is very simple.

The Real class implements the Network interface. Although the Proxy constructor parameter type is Network, classes that implement an interface in java can be directly converted to the interface type.
Network real = new Real ();
Therefore, you can directly pass an instantiated object of the Real class.
This. network. browse (); is actually calling the browse method of the Real class's instantiated object.

Java proxy Mode

This is not like the real proxy mode, right?
The image is simulated.
Net is the Proxy object and calls net. when browse is used, the net check method is called to perform some inspection and other work, and then the browse method of the delegate object is called for real business processing. In fact, the method specified by the delegate object is always executed.
The Proxy class is mainly for the delegate class to pre-process messages, filter messages, and transfer messages to the delegate class and post-processing. The Proxy class does not really implement the service
The Proxy class and InvocationHandler interface provided by Java provide dynamic Proxy class generation
For details, you can refer to the classes and interfaces under java. lang. reflect. In fact, the reflection mechanism of java is mainly used, which is very simple.

The Real class implements the Network interface. Although the Proxy constructor parameter type is Network, classes that implement an interface in java can be directly converted to the interface type.
Network real = new Real ();
Therefore, you can directly pass an instantiated object of the Real class.
This. network. browse (); is actually calling the browse method of the Real class's instantiated object.

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.