JAVA design patterns ---------- Proxy)

Source: Internet
Author: User

JAVA design patterns ---------- Proxy)

Here is a brief introduction to the use of the most basic proxy.

Agency: Simply put, one person or one institution takes action on behalf of another person or another institution. In some cases, a customer does not want or cannot directly reference an object, but the proxy object can play a mediation role before the client and the target object.
The proxy mode provides a proxy object for an object and controls the reference to the original object by the proxy object.

UML diagram

From the figure above, we can see the role involved by the Proxy:

Abstract object role:Declares the common interfaces of the target object and the proxy object, so that the proxy object can be used wherever the target object can be used.

Target object role:Defines the target object represented by the proxy object. (That is, who is the proxy)

Proxy object role:The proxy object contains references of the target object, so that the target object can be operated at any time. The proxy object provides the same interface as the target object, so that the target object can be replaced at any time. A proxy Object usually performs an operation before or after the client call is passed to the target object, instead of simply passing the call to the target object.

 

Here we will demonstrate the relationship between a landlord, intermediary and customer (intermediary is proxy)

1. We need an abstract object role: (Interface)

 

public interface IRenter {public abstract void rent();}

 

2. Target object: (class of the implemented Interface)

 

Public class Renter implements IRenter {@ Overridepublic void rent () {System. out. println ("I Am a landlord and start charging ");}}

 

 

3. The role of the proxy object (Our proxy)

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

 

Object o =Proxy.newProxyInstance(loader, interfaces, h)

 

 

Public class Client {@ Testpublic void Test2 () {final Renter r = new Renter (); // The Proxy Object // o is the Object after the intermediary Proxy o = Proxy. newProxyInstance (Client. class. getClassLoader (), new Class [] {IRenter. class}, new InvocationHandler () {@ Overridepublic Object invoke (Object proxy, Method method, Object [] args) throws Throwable {
// Starting from here, the content to be controlled is intercepted, such as if (method. getName. equals ('rent ') {name the method the rent function to do what you want} // System. out. println ("aaaa"); // The output is System before every simple method. out. println ("billing"); return method. invoke (r, args); // return method. invoke (the object to be proxy, the parameter will be released when any parameter is passed in, this is equivalent to releasing all) ;}); IRenter ir = (IRenter) o; // at last, you need to convert the object into an interface type ir. rent ();}}

Through the simple introduction above, we can find that all methods or functions of a proxy class will be operated only after they are passed through the proxy, and the designated operation method will do what we want to do, no specified direct access.

 

The above is just a simple example. The following is an example of actual use.

We use the connection pool when connecting to the database, but the connections in the connection pool are limited, so we need to put them back into the pool after each use, however, writing a function to put it back into the pool is not easy to use, so we will put con. when close () is used to close the connection, rather than close the connection, it is directly put back into the pool for other threads to call, that is, it is necessary to intercept the close method in con.

The following three roles are required:

1. Interface object connection interface

2. Implement the Connection con = DriverManager. getConnection (url, user, password) object; // you can perform the Connection.

3. Our proxy class is required.

The code for the entire connection pool is as follows:

 

Public class hibernateFactory2 {private static final int NUM = 3; private static List
 
  
Pool = new ArrayList
  
   
(); Static {// read the configuration file Properties p = new Properties (); try {p. load (hibernateFactory. class. getClassLoader (). getResourceAsStream ("jdbc. properties "); // read the value in the file and modify the configuration file until 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
   
    
Object o = Proxy. newProxyInstance (hibernateFactory2.class. getClassLoader (), new Class [] {Connection. class}, new InvocationHandler () {@ Overridepublic Object invoke (Object proxy, Method method, Object [] args) throws Throwable {if (method. getName (). equals ("close") {// intercept the close method pool. add (Connection) (proxy); // return the Connection back to the pool System. out. println ("returns... "); Return null;} return method. invoke (con, args); // all other releases}); pool. add (Connection) o);} // System. out. println ("initialization completed" + con);} catch (IOException e) {// TODO Auto-generated catch blocke. printStackTrace ();} catch (SQLException e) {// TODO Auto-generated catch blocke. printStackTrace ();} catch (ClassNotFoundException e) {// TODO Auto-generated catch blocke. printStackTrace () ;}/// obtain the connection. Public static synchronized Connection getCon () throws Exception {if (pool. size () <= 0) {System. out. println ("no connection in pool"); return getCon ();} System. out. println ("use one .. "); Return pool. remove (0); // both methods are available // while (pool. size () <= 0) {// System. out. println ("A connection has been established in the pool"); // Thread. sleep (1000); // return pool. remove (0 );//}}}
   
  
 

 

Based on the above, we have written a general version

 

Public class proxyUtils {public static Object getProxy (final Object srcobj) {Object o = Proxy. newProxyInstance (proxyUtils. class. getClassLoader (), srcobj. getClass (). getInterfaces (), // you can modify the new InvocationHandler () {@ Overridepublic Object invoke (Object proxy, Method method, Object [] args) throws Throwable {System. out. println ("blocked .... "); // Return method. invoke (srcobj, args) is intercepted here; // We can also perform some Column Operations}); return o ;}}
However, when calling this tool, we must upload an instance object, that is, the implemented class.

 

For example, IA is the implementation class for interface.

A a = new ();

IA ia = (IA) proxyUtils. getProxy ();

You can call the method through the ia object.

 

Another implementation form 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 statement can be modified. If you do not know it, it is best to use new proxyUtils2 (srcobj); return o ;}@ Overridepublic Object invoke (Object proxy, method method, Object [] args) throws Throwable {System. out. println ("intercept here"); Object obj = method. invoke (srcobj, args); // here we can also operate on the returned value, which is also a benefit of proxy return obj ;}}

All of the above are implemented in the proxy design mode. In fact, the proxy mode is equivalent to a secretary, which can help you do what you want.

 

Proxy application (from where others see it)

 

Proxy Mode Application Form

(1) Remote Proxy-you can hide the fact that an object exists in a different address space. The client can also access objects on a remote machine. The remote machine may have better computing performance and processing speed, and can quickly respond to and process client requests.

(2) Virtual Proxy-allows objects with high memory overhead to be created as needed. This object is created only when it is actually needed.

(3) Copy-On-Write Proxy (Copy-On-Write Proxy)-used to control object replication by delaying object replication until the customer really needs it. Is a variant of the virtual proxy.

(4) Protection Proxy-provide different levels of target object Access permissions for different customers

(5) Cache Proxy-provides temporary storage for overhead computing results. It allows multiple customers to share results to reduce computing or network latency.

(6) Firewall Proxy-controls access to network resources and protects the subject from malicious customer attacks.

(7) SynchronizationProxy-Provides secure access to the topic in the case of multiple threads.

(8) Smart ReferenceProxy-provides some additional operations when an object is referenced, such as recording the number of calls to this object.

(9) Complexity HidingProxy: used to hide the Complexity of a complex set of classes and perform access control. It is also called the appearance proxy (Fa? Ade Proxy), which is not hard to understand. The complex hidden proxy and appearance mode are different because the proxy controls access, while the appearance mode is different because the proxy controls access, while the appearance mode only provides 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.