Java and design pattern-proxy pattern

Source: Internet
Author: User

Java and design pattern-proxy pattern

The proxy mode is also called the delegate mode. It is a structural design mode that provides a proxy for other objects to control access to this object. It sounds hard to understand that there are also many examples of agents in life. After graduation, I want to find a house, and how to quickly find my desired house must use a rental agency; if I want to buy a train ticket, the railway station is too far away. We can select a ticket agent to purchase tickets. The UML class diagram of the code mode is as follows:

Application Scenario: when it is difficult to directly access an object or access an object, a proxy object can be used for indirect access. To ensure the transparency of the client, the delegate object and proxy object must implement the same interface. Next we will take the "qiuju lawsuit" as an example to explain the Agency mode. We all know that we have to hire a lawyer in the case of a lawsuit. This lawyer can think of it as our agent. We use him to perform some operations.

First, an abstract class is involved:

Package com. proxy. demo; public abstract class Lawsuit {/*** abstract class */abstract void lawsuit ();}

It is very simple. Just an abstract method. The following is the implementation of the Qiu Ju class, that is, the real class. overwrite the implementation of this abstract method:

Package com. proxy. demo; public class QiuJu extends Lawsuit {/*** real class */@ overriworkflow ID lawsuit () {System. out. println ("I'm Qiu Ju, I'm going to file a lawsuit! ");}}

The following is the proxy class:

Package com. proxy. demo; public class ProxySubject {/*** proxy class */QiuJu qiuJu = null; public ProxySubject (QiuJu qiuJu) {// introduce the chrysanthemum object this by using the constructor. qiuJu = qiuJu;} public void lawsuit () {qiuJu. lawsuit (); // The agent sued Qiu Ju }}

The proxy class does not actually do anything, but calls the method of the real class. The following test classes:

Package com. proxy. demo; public class TestClass {public static void main (String [] args) {QiuJu qiuJu = new QiuJu (); ProxySubject proxySubject = new ProxySubject (qiuJu); proxySubject. lawsuit (); // call the method through proxy }}

Run the Test method:

We can see that the proxy has successfully implemented the method of the real class. By the way, adjust the font size of the console:

Open window-preferences -- general-appearance-colors and fonts -- debug-console font.

Proxy mode is a very common method. Careful friends will find that we used the proxy mode in the previous article "rule mode. The proxy mode can be roughly divided into two parts: static proxy and dynamic proxy. The above is a static proxy. The proxy code is compiled by the programmer himself or by using some automated tools to generate fixed code. That is to say, before our code runs, the class compilation file of the proxy class already exists. The dynamic code dynamically generates the proxy object through the reflection mechanism, and the proxy will decide who will be in the execution phase. Java also provides us with a convenient dynamic proxy interface InvocationHandler. To implement this interface, we need to rewrite its call method invoke. That is to say, we must first improve this dynamic proxy class:

package com.proxy.demo;import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;public class DynamicProxy implements InvocationHandler {Object object=null;public DynamicProxy(Object object) {this.object = object;}@Overridepublic Object invoke(Object proxy, Method method, Object[] args) throws Throwable {Object  result=method.invoke(object, args);return result;}}

Interface InvocationHandler: this Interface defines only one Method Object: invoke (Object obj, method Method, j2eejavalanguage jdk1.4apijavalangobject.html "> Object [] args ). In actual use, the first parameter obj generally refers to the proxy class, and the method is the method to be proxy. In the preceding example, request () and args are the parameter arrays of this method. This abstract method is dynamically implemented in the proxy class.
In the past, the tasks handled in the proxy class were handed over to InvocationHandler, and no longer concerned about who the proxy is.

Modify the test class as follows:

Package com. proxy. demo; import java. lang. reflect. proxy; public class TestClass {public static void main (String [] args) {/** QiuJu qiuJu = new QiuJu (); ProxySubject proxySubject = new * ProxySubject (qiuJu); proxySubject. lawsuit (); // call method through proxy */Lawsuit lawsuit = new QiuJu (); DynamicProxy dynamicProxy = new DynamicProxy (lawsuit); ClassLoader loader = lawsuit. getClass (). getClassLoader (); // obtain the ClassLoader of the Proxy class // dynamically construct a Proxy Lawsuit lawyer = (Lawsuit) Proxy. newProxyInstance (loader, new Class [] {Lawsuit. class}, dynamicProxy); lawyer. lawsuit ();}}


Note: For dynamic proxy, the Lawsuit becomes an interface, and the QiuJu class becomes an implementation interface.

Run the instance. The result is the same as that of the static Proxy:

It can be seen that the dynamic proxy class can act as a proxy for N proxy classes. Its essence is to decouple the proxy class and the proxy class, so that there is no direct Decoupling Relationship Between the two, making it more flexible to use. Static proxy is more in line with the object-oriented idea, and can implement proxy as needed during development.

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.