Proxy mode (1)-static to dynamic

Source: Internet
Author: User
Tags call back
Story

After a weekend holiday, sun went to bed until and said goodbye to Zhou Gong. Mr. Wang is preparing to go to the canteen to buy meals. As a good master, Mr. Wang takes the initiative to help Mr. Sun bring meals. Sun ordered rice, kung pao chicken, and fenda. Sun gets up to wash his clothes, and waits for a long time. John is a good manager. Next we will first abstract this story, a painting image. This class chart is the proxy mode.

Proxy mode definition: provides a proxy for other objects to control access to this object. How can this sentence be understood? From the perspective of life, object A is used to replace object B to deal with things that should have been done by object B. For example, the example of buying a meal above, such as buying a ticket through scalpers, etc. From the code point of view, it is: Use object A to filter and pre-process calls to object B. From any perspective, the proxy must have all the methods that the actual object needs to be proxy.
The static proxy class diagram is shown above, and the definition is also read. Next we will look at the code according to the class diagram.
Interface (dormitory Member)
/*** Dormitory member interface * development time: 9:17:19 */public interface dormitorymember {// buy the staple food public Boolean buystaplefood (string staplefoodname ); // public Boolean buydish (string dishname); // public Boolean buydrink (string drinkname );}
Proxy (dormitory Director)
// Proxy class public class dormitorymemberproxy implements dormitorymember {// hold a proxy object private dormitorymember; // input the proxy object public partition (dormitorymember) {This. dormitorymember = dormitorymember;} // The agent buys the staple food public Boolean buystaplefood (string staplefoodname) {return dormitorymember. buystaplefood (staplefoodname);} // The Public Boolean buydish (string dishname) {return dormitorymember. buydish (dishname);} // public Boolean buydrink (string drinkname) {return dormitorymember. buydrink (drinkname );}}
Actual class (Sun)
// Actual class public class dormitorymemberimpl implements dormitorymember {// buy staple food public Boolean buystaplefood (string staplefoodname) {try {system. out. println ("buy staple food" + staplefoodname);} catch (exception e) {return false;} return true ;}// purchase public Boolean buydish (string dishname) {try {system. out. println ("dishes:" + dishname);} catch (exception e) {return false;} return true;} // public Boolean buydrink (string drinkname) {try {system. out. println ("buy a drink:" + drinkname) ;}catch (exception e) {return false;} return true ;}}
The story continues. the dormitory chief went to the dining room to buy food. As a result, the dormitory went back with rice and food for a long time. It was difficult for sun to swallow rice and food without drinks. However, it is hard to say that the dormitory is long. You will have lunch. At the time of dinner, Sun was kill in the league of legends, and he had no time to buy food. So he fell into the good house manager. This time, Mr. Sun was smart and told the chief that if something he ordered was absent, he would call back and decide what to buy.
The problem is that the demand has changed. If there is no demand for the child, call the child to decide whether to buy or not. This phone number is naturally called by the dormitory director. So we need to modify the proxy class! This is the benefit of using the proxy mode. we disable the modification to the actual class. The modified code of the proxy class is as follows:
// Proxy class public class dormitorymemberproxy implements dormitorymember {// hold a proxy object private dormitorymember; // input the proxy object public partition (dormitorymember) {This. dormitorymember = dormitorymember;} // The agent buys public Boolean buystaplefood (string staplefoodname) {Boolean buysuccess = dormitorymember. buystaplefood (staplefoodname); If (buysuccess = false) {system. out. println ("Call Sun"); Return false;} else {return true ;}// the agent buys public Boolean buydish (string dishname) {Boolean buysuccess = dormitorymember. buydish (dishname); If (buysuccess = false) {system. out. println ("Call Sun"); Return false;} else {return true ;}// buy drinks by proxy public Boolean buydrink (string drinkname) {Boolean buysuccess = dormitorymember. buydrink (drinkname); If (buysuccess = false) {system. out. println ("Call Sun"); Return false;} else {return true ;}}}
Question (1) You can see the code. We need to make the same changes to every method in the proxy class. The limit assumes that we have implemented 1000 methods for this interface.
Question (2) ultimate hypothesis: The Great dormitory manager not only buys meals for Sun, but also buys clothes for Xiao Li and computers for Xiao Zhao. In other words, the dormitory administrator needs to proxy different interfaces. But this is not possible, because the actual classes held by the proxy class are definite, that is, each proxy class can only be used as an excuse.
Obviously, this is not scientific. So many codes are repeated. If there is an unscientific situation, there will naturally be a way for this. The biggest fear is that no problems are found, and no improvement can be made without any problems. Next we will go to dynamic proxy.
Dynamic proxy first, let's look at Question 1, since the preprocessing in the proxy class is the same when calling the actual class, we only need to ensure that the actual class is returned to a certain processing before or after the actual class is called. Of course, it seems that I have never learned how to return a function for many different methods, because the number and type of class parameters and return values are inconsistent. Therefore, Java has a special interface to implement this function, the invocationhandler interface.

Let's look at Question 2. For question 2, we must decouple the proxy class from the proxy class. Usually we solve this type of problem by using reflection. This is no exception. Here, the reflection mechanism provided by Java can generate a proxy class at runtime, that is, a dynamic proxy. This blog is too long. Please separate it. First, paste the dynamic proxy code. The actual classes and interfaces have not changed!

Agent Factory
Import Java. lang. reflect. proxy; // proxy factory class public class proxyfactory {// actual class private object target; Public proxyfactory (object target) {this.tar get = target ;} // generate the proxy public object getinstance () {// instantiate a pre-processing object that inherits the invocationhandler interface proxyhandler handler = new proxyhandler (target) according to the passed-in actual class ); // obtain the proxy class return proxy through reflection. newproxyinstance (target. getclass (). getclassloader (), target. getclass (). getinterfaces (), Handler); // handler is the method call for centralized processing on the dynamic proxy class Object }}
Inherits the handler class of the invocationhandler Interface
Import Java. lang. reflect. invocationhandler; import Java. lang. reflect. method; public class proxyhandler implements invocationhandler {private object target; Public proxyhandler (Object target?#this.tar get = target;} // public Processing Method of All proxy Methods public object invoke (Object proxy, method method, object [] ARGs) throws throwable {object result = NULL; Result = method. invoke (target, argS); // If (result. tostring (). equals ("false") {system. out. println ("Call Sun"); return result;} else {return result ;}} public class client {public static void main (string [] ARGs) {// The Real proxy class is forced to dormitorymember = (dormitorymember) New proxyfactory (New dormitorymemberimpl () on the client ()). getinstance (); dormitorymember. buystaplefood ("rice ");}}

Summary:The dynamic proxy unbinds the coupling between the proxy class and the actual class through reflection, and simultaneously processes the proxy methods in a unified manner by inheriting the handler class of the invocationhandler interface. It also solves the problems encountered by the static proxy.

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.