Proxy mode (proxy [delay] mode)

Source: Internet
Author: User
Proxy ??

Proxy refers to a person who works on behalf of others. The proxy actually uses the delegate mechanism. During the proxy process, you can do something else and then execute the code of the proxy object.

  • Knowledge reserve

1. When to use:

The gof book (see Appendix E [gof]) describes the proxy mode by using a text editor that can embed graphical objects (such as examples) in the text as an example. To generate these image objects, it is time consuming to read image files. Therefore, if some graphic objects are generated when a document is opened, it may take too long to open the document. Therefore, it is best to generate an instance when the user browses various graphic objects in the text. In this case, the proxy mode is useful.

2. There are proxies:

  • Virtual proxy (Virtual proxy) virtual proxy is the proxy mode learned in this chapter. An instance is generated and initialized only when an instance is actually needed.
  • Remote proxy (remote proxy) remote proxy allows us to call realsubject methods just as transparently as it is on the remote network. Java RMI (remotemethodinvocation: Remote method call) is equivalent to remote proxy.
  • Access proxy access proxy is used to set access restrictions when calling the functions of the realsubject role. For example, this proxy can only allow specified users to call methods, and an error is reported when other users call methods.

  • Static proxy
    1. Use the delegated agent to act as the proxy for issues that can be solved. When a problem cannot be solved, it will still be handed over to me.
    Here, "transfer" refers to the "Commission" that has been mentioned many times in this book ". Calling the real. Print method from the print method of the printerproxy class is a reflection of this "delegate.

  1. The printerproxy class can be separated from the printer class and used as an independent component. Any class that implements the printable interface can assume the role of proxy. Reflection instance required
Private synchronized void realize (string classname) {If (real = NULL) {try {real = (printable) class. forname (classname ). newinstance ();} catch (classnotfoundexception e) {system. out. println ("not found" + classname);} catch (exception e) {e. printstacktrace ();}}}
  • Dynamic proxy

In the dynamic proxy mechanism of Java, there are two important classes or interfaces: invocationhandler (Interface) and proxy (class ), this class and interface are required to implement our dynamic proxy. First, let's take a look at how the Java API help documentation describes these two classes:
Invocationhandler:

InvocationHandler is the interface implemented by the invocation handler of a proxy instance. Each proxy instance has an associated invocation handler. When a method is invoked on a proxy instance, the method invocation is encoded and dispatched to the invoke method of its invocation handler.

Each dynamic proxy class must implement the invocationhandler interface, and each proxy class instance is associated with a handler. When we call a method through a proxy object, the call of this method will be forwarded to the invocationhandler interface's invoke Method for calling. Let's take a look.
Is the only method of the invocationhandler interface? Invoke? Method:
Object invoke(Object proxy, Method method, Object[] args) throws Throwable

We can see that this method accepts three parameters in total. What do these three parameters represent?

Object invoke (Object proxy, method, object [] ARGs) throws throwableproxy: refers to the real object method we represent: it refers to the method object ARGs for calling a method of a real object: it refers to the parameter accepted when calling a method of a real object.
Clarify responsibilities
  • Implement a printer with a name
    Description
    Printer | indicates a printer class with a name (myself)
    Printable | common interfaces of printer and printerproxy
    Printerproxy | indicates a printer class (agent) with a name)
    Main | class for testing program behavior
UML

Class diagram:

Sequence diagram:

Code
  • Printable
Public interface printable {// set the Print name void setprintername (string name); // obtain the Print name string getprintername (); // display the text void print (string );}
  • Printer

···
Public class printer implements printable {
Private string name;

Public printer () {heavyjob ("generating printer instance");} public printer (string name) {This. name = Name; heavyjob ("generating printer instance (" + name + ")");} /*** simulate a high-Load Task * @ Param string */private void heavyjob (string) {system. out. println (string); For (INT I = 0; I <5; I ++) {try {thread. sleep (1000);} catch (interruptedexception e) {e. printstacktrace ();} system. out. print (". ") ;}@ overridepublic void setprintername (string name) {This. name = Name ;}@ overridepublic string getprintername () {return name ;}@ overridepublic void print (string) {system. out. println ("=" + name + "="); system. out. println (string );}

}

···

  • Printerproxy
Public class printerproxy implements printable {private string name; private printer real;/*** no matter how many times the setprintername method and getprintername method are called, * No printer class instance will be generated. Only when you really need me * Will the printer class instance be generated (the caller of the printerproxy class does not know whether the user has generated me or whether the user has generated me ). * @ Param name */Public printerproxy (string name) {This. Name = Name;} @ override public synchronized void setprintername (string name) {If (real! = NULL) {real. setprintername (name);} This. name = Name ;}@ override Public String getprintername () {return name ;}@ override public void print (string) {realize (); real. print (string);} private synchronized void realize () {If (real = NULL) Real = new printer (name );}} public class Maint {public static void main (string [] ARGs) {printable P = new printerproxy ("Tom"); system. out. println ("now" + P. getprintername (); p. setprintername ("cat"); system. out. println ("now" + P. getprintername (); p. print ("I am Tomcat ");}}
  • Result:
Now Tom is now cat is generating printer instance (CAT)... === cat === I am Tomcat
Dynamic proxy code
Public class client {public static void main (string [] ARGs) {printable Tom = new printer ("Tom"); dynamicproxy proxy = new dynamicproxy (Tom ); printable o = (printable) proxy. newproxyinstance (proxy. getclass (). getclassloader (), Tom. getclass (). getinterfaces (), proxy); system. out. println (O. getclass (). getname (); system. out. println ("now" + O. getprintername (); O. print ("Tomcat") ;}} public class dynamicproxy implements invocationhandler {private object; Public dynamicproxy (Object object) {This. object = object;} @ override public object invoke (Object proxy, method, object [] ARGs) throws throwable {system. out. println ("prepare for execution"); system. out. println ("method:" + method); object o = method. invoke (object, argS); system. out. println ("execution completed"); return o ;}} public interface printable {// set the Print name void setprintername (string name); // obtain the Print name string getprintername (); // display text void print (string);} public class printer implements printable {private string name; Public printer () {heavyjob ("generating printer instance ");} public printer (string name) {This. name = Name; heavyjob ("generating printer instance (" + name + ")");} /*** simulate a high-Load Task * @ Param string */private void heavyjob (string) {system. out. println (string); For (INT I = 0; I <5; I ++) {try {thread. sleep (1000);} catch (interruptedexception e) {e. printstacktrace ();} system. out. print (". ") ;}@ override public void setprintername (string name) {This. name = Name ;}@ override Public String getprintername () {return name ;}@ override public void print (string) {system. out. println ("=" + name + "="); system. out. println (string );}}

Proxy mode (proxy [delay] mode)

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.