JAVA design Mode (24)-Agent (proxy) mode __java

Source: Internet
Author: User
Tags aop reflection throwable

Definition: provides a proxy for other objects to control access to this object.

Type: Object-structured pattern

class Diagram:



roles involved in proxy mode

Abstract Theme Role (Subject): declares a common interface between the agent theme and the real topic, so that any place that needs a real topic can be replaced with a proxy theme. Agent Theme Role (proxy): a reference to a real topic that allows you to manipulate real topics at any time. The agent's theme provides the same interface as the real theme, allowing it to replace the real theme at any time. By holding a reference to the real topic, the agent theme can not only control the creation or deletion of the real topic, but also intercept the real topic before it is invoked or do some action after the call. Real proxy object (realsubject): defines the specific object represented by the proxy role (proxy).

Why do we have to control the access rights of the object? One reason is to delay the creation and instantiation of objects (lazy instantiation)through control until the object is really needed for creation and instantiation. Because some object creation and instantiation require a large amount of system resources, we are not sure that the user will call the object, so delay object instantiation to slow down system resource consumption. For example, the document editor such as Word, we can insert links, pictures, and so on, but not every time we open word there are create and instantiate these objects, especially the instantiation of the picture object is very consuming resources, and we need to instantiate all the pictures. When we look at word, we just see a part of it, so there's no need to instantiate the resource, and it's not too late to instantiate it when we look at the next page.



Code implementation

Abstract role (Subject)

Interface subject{public
	void request ();
}

Real Role (Realsubject)

Class Realsubject implements subject{

	@Override public
	Void request () {
		System.out.println ("Request ...") ;
	}
}

Agent Role (proxy)

Class Proxysubject implements subject{
	
	private Realsubject realsubject;//The properties of a real role as the proxy role  
	
	@Override
	public void request () {
		
		prerequest ();
		
		if (realsubject==null) {
			realsubject = new Realsubject ();
		}
		
		Realsubject.request ();//Here executes the request method of the Real object  
		
		postrequest ();
	}
	
	public void Prerequest () {	//preprocessing
		System.out.println ("before request ...");
	}
	public void Postrequest () {	//post-processing
		System.out.println ("After request ...");
	}

Customer role (client)

public class Proxyclient {public

	static void Main (string[] args) {
		
		Subject Subject = new Proxysubject ();
		Subject.request ();
		
	}


From the example above, you can see how the proxy mode works. First, because both the agent theme and the real topic implement a common interface. This allows us to replace the original interface, as long as the actual subject object, can be replaced by the agent theme. Second, the agent theme plays a mediating role between the customer and the real subject. Using this mediation platform, we can do some necessary preprocessing (AOP) beforepassing the customer request to the real topic.


Java support for proxy mode---dynamic proxy
Above the proxy, we force the proxy class redwineproxy to implement the abstract interface Sellinterface. This causes our proxy class to not be universal to other interfaces, so we have to implement a proxy class for each interface. Fortunately, Java provides support for proxy mode.
Java is mainly through the proxy class and Invocationhandler interface to achieve the support of proxy mode.

Java Proxy Mechanism implementation code:

/** * Proxy class must implement the Invocationhandler interface */public class Proxyobject implements Invocationhandler {private Object proxy_obj;
	Proxyobject (Object obj) {this.proxy_obj = obj;
		public static object factory (Object obj) {Class cls = Obj.getclass (); Returns the proxy object return Proxy.newproxyinstance (Cls.getclassloader (), Cls.getinterfaces (), new P by the Newproxyinstance method of the proxy class
	Roxyobject (obj)); /** * Implement Invocationhandler interface invoke/public object Invoke (Object proxy, mode method, object[] args) throws
		Throwable {System.out.println ("blocked before function call:" + method);
			if (args!= null) {//print parameter list System.out.println ("method has" + args.length + "parameters");
			for (int i = 0; i < args.length i++) {System.out.println (args[i]);
		The method of dynamically invoking the original object using reflection mechanism Object mo = Method.invoke (proxy_obj, args);
		SYSTEM.OUT.PRINTLN ("Process after function call:" + method);
	return mo; }//test code public static void Main (String agr[]) {isubject subject = (Isubject) factory (New Proxysubject ());
	Subject.request (); }
}

It can be seen from the above code that the proxy theme Proxyobject class does not implement the Isubject interface we defined, but rather implements the Java Invocationhandler interface. This separates the agent theme role from our business code, allowing the proxy object to be universal to other interfaces.
In fact, the Invocationhandler interface is an interception mechanism. When a proxy object is in the system, the invocation of the original object (real subject) method is processed by the Invocationhandler interface, and the method information is passed to the Invoke method as a parameter. In this way, we can intercept the invocation of the original object in the Invoke method and invoke the method of the original object dynamically through the reflection mechanism. This seems to be the foundation of Spring AOP programming as well.


The following implements a simple AOP blocking mechanism

This example intercepts the functions we specify and processes them as needed before and after the intercept.

Slice interface, define the processing method before and after we call

/**
 * Interface, by implementing this interface, we can process the specified function before and after the call
 /
interface Aopinterface {public
	void before (Object obj); Processing of the call public

	void End (Object obj);//processing after the call
}

Slice interface implementation class, implement processing logic

Class Aopinterfaceimp implements Aopinterface {
	
	@Override public
	void before (Object obj) {
		//add your Operation here
		System.out.println ("Intercept before Calling");
	}

	@Override public
	void End (Object obj) {
		//add your operation here
		System.out.println ("Call after call processing");
	}

proxy class implementation code:

Class Proxyobject implements Invocationhandler {Private Aopinterface aop;//defines the method that is called when the entry is private Object proxy_obj;
		Private String methodname;//Specifies the method name to be cut Proxyobject () {} Public Object factory (Object obj) {proxy_obj = obj;
		Class cls = Obj.getclass ();
	Return Proxy.newproxyinstance (Cls.getclassloader (), cls.getinterfaces (), this); public object invoke (object proxy, Method method, object[] args) throws Throwable {if (THIS.AOP = null) thro
		W New NullPointerException ("AOP is null");

		if (method = = null) throw new NullPointerException ("method is null");
		Object o; If you specify that you want to block the method name, and the method that you call is the same as the specified method name, intercept processing//Otherwise, if (MethodName!= null && method.tostring () is handled by the normal method. IndexOf (Metho
			dname)!=-1) {Aop.before (proxy_obj);//To specify the processing o = Method.invoke (proxy_obj, args) before the method call;
		Aop.end (proxy_obj);//To specify the processing after the method call} else {//no method specified, call o = Method.invoke in normal method (Proxy_obj, args);
	return o;
	Public Aopinterface Getaop () {return AOP;
}
	public void Setaop (Aopinterface aop) {THIS.AOP = AOP;
	Public String Getmethodname () {return methodname;
	} public void Setmethodname (String methodname) {this.methodname = methodname; }
}

Target interface (object to be intercepted) code:

The target interface (the interface that needs to be intercepted)
interface subinterface {public

	void login (string userName, string password);

	public void Access (String res);

Target interface Implementation Class code:

Class Subinterfaceimpl implements Subinterface {

	@Override public
	void Login (string userName, string password) {
		System.out.println ("Subinterfaceimpl Login (" + UserName + ","
				+ password + ")");
	}

	@Override public
	void Access (String res) {
		System.out.println ("Subinterfaceimpl access (" + res +) ");

}

Test Class Code:

public class Aopdemo {public

	static void Main (string[] args) {

		Proxyobject proxy = new Proxyobject ();

		PROXY.SETAOP (New Aopinterfaceimp ())//The Intercept processing object that we implement
		Proxy.setmethodname ("Access");//Specify the function to intercept

		subinterface Si = (subinterface) proxy.factory (New Subinterfaceimpl ());
		Because the login method is not the Intercept function we specify, AOPINTERFACEIMP is not executed
		si.login ("tt", "12345");

		Access is the interception method that we specify, so the
		two methods
		si.access ("Authentication") for Aopinterfaceimp//objects are executed

	before and after the call to access.



It can be seen from above that interception mechanism is one of the important ways of using proxy mode.

In addition to blocking, proxy mode is often used for resource loading. When we want to load the resources very large, we can let the real theme role in the background load resources, let the agent theme role is responsible for processing the waiting for the foreground information.
And there is the authorization mechanism. The ability to intercept real topics through proxies to control access to real-world topics.



Applicable Scenarios

Use proxy mode when you need to replace a simple pointer with a more generic and complex object pointer. Here are some common scenarios where you can use proxy mode:

Remote Proxy : Provides a local-domain representation object for an object located in a different address space. This different address space can be in this machine, but also in another machine. The remote agent is also called the Ambassador (Ambassador). The advantage is that the system can hide the details of the network so that the client does not have to consider the existence of the network. The client is fully capable of assuming that the object being represented is local rather than remote, and that the agent is responsible for most of the network communications work. Because the customer may not realize that it will start a time-consuming remote call, the customer is not necessarily prepared. Virtual Proxy (example of a picture delay loading): Create a resource-consuming object as needed so that the object is actually created only when it is needed. The advantage of using virtual proxy mode is that the proxy object can load the object that is being represented when necessary, and the agent can optimize the loading process as necessary. When a module is loaded with resources, the benefits of virtual proxies are obvious. Protection Agent (Protection proxy): Controls access to the original object. The protection agent is used when the object should have different access rights. copy-on-write Agent : A kind of virtual agent. Delay replication (cloning) until the client needs it to take action. Smart Reference Proxy : When an object is referenced, provide some extra action, such as logging the number of calls to this 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.