----------Proxy mode of JAVA design pattern (proxy) __java

Source: Internet
Author: User
Tags throwable

here is simply a brief introduction to the use of the most basic agents.


Agent, Popular Point said: is a person or an organization on behalf of another person or another agency to take action.

In some cases, a customer does not want to or cannot refer directly to an object, and the proxy object can be

End and target objects before they act as intermediaries.
The proxy mode provides a proxy object to an object, and the proxy object controls the reference to the original object.


UML Diagrams

From the above diagram we can see the role the agent is involved in:

Abstract Object role: declares a common interface between the target object and the proxy object.

This allows proxy objects to be used wherever the target object can be used.

target Object role: defines the target object that the proxy object represents. (i.e. who is to be represented)

proxy Object role: the proxy object contains a reference to the target object, so that you can

Manipulate the target object; The proxy object provides the same interface as the target object, so that the target object can be substituted at any time.

A proxy object typically performs an operation before or after a client call is passed to the target object, rather than simply calling the

Passed to the target object.


Here we demonstrate a landlord, intermediary and customer relationship (intermediary is the agent)

1, we need an abstract object role: (interface)

Public interface Irenter {public
	abstract void rent ();
}

2, we need the target object: (is the implementation of the interface of the class)

public class Renter implements irenter{
	@Override the public
	void rent () {
		System.out.println ("I am the landlord, start charging Cluck");
	}
}


3, the role of the proxy object (is our agent)

We need to use the class used by the proxy in Java

Object o =proxy.newproxyinstance (loader, interfaces, h)

The public class Client {@Test the public
	void Test2 () {
		 final renter R =new renter ();//The Object//O by the agent
		is the object after the mediation agent
		Object o =proxy.newproxyinstance (Client.class.getClassLoader (),
								new class[]{irenter.class},new Invocationhandler () <span style= "White-space:pre" >								</span>{
									@Override public
									Object invoke (Object Proxy, Method method, object[] args)
											Throws Throwable {
		Starting here is to start intercepting the content you want to control, such as if (Method.getName.equals (' rent ')) {The function named rent, make the thing you want}
//										System.out.println ("AAAA");//Here is simply the output of each method before the
										System.out.println ("collection fee");
										Return Method.invoke (R, args); <span style= "font-family: ' ms Shell Dlg ';" >return Method.invoke (to proxy objects, parameters passed in what parameters to release what parameters, here is the equivalent of all open);

									}
								);
		Irenter ir = (irenter) o;//The last time the object needs to  be  strongly converted to an interface type
		ir.rent ();
	}


through the above simple introduction, can find, a proxy class of all methods or functions, have to go through the agent, before the operation, specify the method of operation to do what we want to do, without the specified direct release

The above is just a simple introductory example, and here's a practical example of how to use it.

When we connect to the database, we are using the link pool, but the link pool is a limited number of connections,

So we need to put it back in the pool after each run, but write a function individually to put it back in the pool, it's not very useful,

So, we turn the Con.close () off the connection, not off, but directly into the pool,

Let the other threads call, that is, you need to intercept the Close method inside the con.

Three roles required:

1, Interface object connection interface

2, to implement the object Connectioncon=drivermanager.getconnection (URL, user, password), and/or in the connection can be.

3, we need the proxy class.

Here's the code for the entire connection pool:

public class HibernateFactory2 {private static final int num=3;
	private static list<connection> pool =new arraylist<connection> ();		
			static{//Read config file properties P =new properties ();
				try {p.load (HibernateFactory.class.getClassLoader (). getResourceAsStream ("jdbc.properties"));
				Read the value inside, always modify the configuration file String driver=p.getproperty ("Driver");
				String url=p.getproperty ("url");
				String User=p.getproperty ("username");
				String password=p.getproperty ("password");
				System.out.println (Driver+url+user+password);
				Class.forName (driver);
					for (int i=0;i<num;i++) {final Connection con=drivermanager.getconnection (URL, user, password); The use of dynamic agents began to connection interface implementation of the proxy, con.close, to achieve </span><span style= "color: #ff0000;" >object o =proxy.newproxyinstance (HibernateFactory2.class.getClassLoader (), New Class[]{connection.class}, new I Nvocationhandler () {@Override public object invoke (object proxy; Object[] args throws Throwable {if (Method.getname (). Equals ("Close")) {//intercept Close method Pool.add ((Connection) (proxy))//The connection is returned to the pool System.out.println ("changed back ...)
										");
									return null;
					Return Method.invoke (con, args);//All remaining release}});
				Pool.add ((Connection) o);
			}//System.out.println ("initialization Complete" +con);
			catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();
			catch (SQLException e) {//TODO auto-generated catch block E.printstacktrace ();
			catch (ClassNotFoundException e) {//TODO auto-generated catch block E.printstacktrace ();
	//Below is getting the connection. public static synchronized Connection Getcon () throws exception{if (Pool.size () <=0) {System.out.println ("not already in pool
			Connection ");
		return Getcon (); System.out.println ("Use a..
		"); 
		Return Pool.remove (0); Both methods are possible//while (Pool.size () <=0) {//System.out.println ("There is no connection in the pool");//Thread.sleeP (1000);
}//Return Pool.remove (0);

 //	}
	
}}

On top of that, we've written a generic version

public class Proxyutils {public
	
	static object GetProxy (final Object srcobj) {
		object o = Proxy.newproxyinstance p RoxyUtils.class.getClassLoader (),
							Srcobj.getclass (). Getinterfaces (),//This sentence can be modified by the
							new Invocationhandler () {
								
								@Override Public
								object Invoke (Object proxy, Method method, object[] args)
										throws Throwable {
									System.out.println ("was volley ....") ")//Here uses
									The Intercept  return Method.invoke (srcobj, args);//Returns the value we can also do some column operations
								}
							}
				);
		Return o.
	}
}
But when we call this tool, we must pass in an instance object, which is the implemented class

such as IA for interface A as implementation class

A =new a ();

IA ia = (IA) proxyutils.getproxy (a);

You can invoke the method through the object of IA.


Another form of implementation of the above method

public class PROXYUTILS2 implements invocationhandler{
	private Object srcobj;
	Public proxyUtils2 (Object srcobj) {
		this.srcobj=srcobj;
	}	
	public static object GetProxy (Final object srcobj) {
		object o = Proxy.newproxyinstance ( ProxyUtils2.class.getClassLoader (),
							Srcobj.getclass (). Getinterfaces (),//This sentence can be modified, in the case of unknown, this method is best 
							new PROXYUTILS2 (Srcobj));				
		return o;
	}
	@Override Public
	object Invoke (Object proxy, Method method, object[] args)
			throws Throwable {
			SYSTEM.OUT.PRINTLN ("Use interception here");
			Object obj =method.invoke (srcobj, args);//Here we can also operate on the returned value, which is also the benefit of the proxy return
			obj;	
	}


These are implemented by proxy design mode, in fact, the agent model is equivalent to a secretary, can help you do what you want to do.


Agent application (from where others see)

application Forms of Proxy mode

(1) Remote proxy-You can hide the fact that an object exists in a different address space. Also enables clients to access objects on remote machines, the remote machine may have better computational performance and processing speed, and can quickly respond to and process client requests.

(2) Virtual proxy – allows objects with large memory overhead to be created when needed. We only create when we really need this object.

(3) Write-time replication agent (Copy-On-Write proxy) – Used to control the replication of objects by delaying the replication of the object until the customer really needs it. is a variant of the virtual agent.

(4) Protection agent (Protection (Access) proxy) – provides different levels of target object access to different customers

(5) Cache proxy – provides temporary storage for costly operations results that allow multiple customers to share results to reduce computation or network latency.

(6) Firewall agent (Firewall proxy) – Controls access to network resources and protects topics from malicious customers.

(7) Synchronous agent (Synchronizationproxy) – Provides secure access to topics in multi-threaded situations.

(8) Intelligent Reference Agent (Smart Referenceproxy)-When an object is referenced, provide some additional actions, such as recording the number of calls to this object.

(9) Complex hidden agent (complexity Hidingproxy) – The complexity of hiding a complex set of classes, and access control. Sometimes called the appearance agent (Façade proxy), this is not difficult to understand. Complex hidden agents and skin patterns are not the same because the proxy controls access and the appearance pattern is different because the proxy controls access and the skin mode provides only another set of interfaces.


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.