Talk about the proxy pattern of Java to know a

Source: Internet
Author: User
Tags net time

 I. The role of intermediary segregation

Proxy mode, first contact with it, is in learning. NET time to read a book, called "Big Talk design mode", has been nearly three years now. I believe that the students who have read this book, all remember the agency model in the book, is to do the story of marrying clothes for others. OK, let's go back to the definition of proxy mode: Provides a proxy for other objects to control access to this object. In some cases, an object does not fit or cannot directly refer to another object, whereas a proxy object can mediate between the client and the target object, characterized by the same interface as the proxy class and the delegate class. Proxy mode is a common Java design pattern.

The form of expression is as follows:


The above picture is the initial understanding of the proxy model.


second, the opening and closing principle, increase function,

Now there is a further understanding. The proxy class is more than just an intermediary that isolates clients and delegate classes. We can also use the agent to add some features, without the need to modify the original code, serious compound open and close principle oh.

The proxy class is mainly responsible for preprocessing the message, filtering the message, forwarding the message to the delegate class, and processing the message afterwards. There is usually an association between the proxy class and the delegate class, and the object of a proxy class is associated with an object of a delegate class, and the object of the proxy class does not actually implement the service, but instead provides a specific service by invoking the related method of the object of the delegate class.

In this way, real business functions are implemented with a delegate class, but some of the public services before implementing the business class. For example, in the development of the project we did not join the buffer, log these functions, later want to join, we can use the proxy to implement, and there is no need to open the already packaged delegate class.

III. Classification of agents

According to the above understanding of the agent, for the specific implementation of the agent, we have different ways, if the agent in accordance with the creation period, the proxy class can be divided into two kinds. : Static agent, dynamic agent.
Static proxy: The source code is generated automatically by the programmer or a specific tool, and then compiled. Before the program runs, the. class file for the proxy classes already exists.
Dynamic Agent: Use the reflection mechanism to create the process dynamically while the program is running.

1. Static Agent

Let's look at the static proxy first. It takes only three steps to achieve. First, we need to define the business interface, the business interface implementation class, then define the proxy class, and implement the business interface; finally write a client to invoke.

First: you need to define a business interface, a business interface implementation class

<span style= "FONT-FAMILY:KAITI_GB2312;FONT-SIZE:18PX;" >    /**      * Define a business interface      * @author Cassie      *      /public interface Account {          //query public         void Queryaccount ();            Modify public          void Updateaccount ();        }  <pre name= "code" class= "java" >    /**      * Interface implementation class (including business logic)      *  i.e.: Delegate class     * @author Cassie       */ Public      class Accountimpl implements account{                @Override public          void Queryaccount () {              System.out.println ("Query method ...");                @Override public          void Updateaccount () {              System.out.println ("Modify Method ...");}            } </span>


  

   Second: Define proxy classes, implement business interfaces   

<span Style= "FONT-FAMILY:KAITI_GB2312;FONT-SIZE:18PX;" >/** * proxy class (Enhanced Accountimpl function) * @author Cassie */public class Accountproxy implements account{private Accounti        MPL Accountimpl;          /** * Overrides the default constructor * @param Accountimpl: The object that really wants to execute the business */public Accountproxy (Accountimpl Accountimpl) {      This.accountimpl =accountimpl;          } @Override public void Queryaccount () {System.out.println ("before Business processing ...");          Call the method of the delegate class, which is the specific business method Account>impl.querycount ();      SYSTEM.OUT.PRINTLN ("After business processing ...");          } @Override public void Updateaccount () {System.out.println ("before Business processing ...");          The method of invoking the delegate class;          Accountimpl.updateaccount ();        SYSTEM.OUT.PRINTLN ("After business processing ..."); }} </span> 

Third: Write the client, I write here the test class.
<span style= "FONT-FAMILY:KAITI_GB2312;FONT-SIZE:18PX;" >/**  * Test Account class  * @author Cassie *  /public class Testaccount {public      static void Main (string[] args ) {          Accountimpl Accountimpl = new Accountimpl ();          Here the business object to invoke        accountproxy accountproxy = new Accountproxy (ACCOUNTIMPL) is passed in.         Both methods are enhanced to begin invoking the method of the business object.        Accountproxy.updateacc>ount ();          Accountproxy.queryaccount ();      }  }  </span>
See the execution Effect:
<span style= "FONT-FAMILY:KAITI_GB2312;FONT-SIZE:18PX;" ...</span> before > Business process
<span style= "FONT-FAMILY:KAITI_GB2312;FONT-SIZE:18PX;" > Modification Method ...</span>
<span style= "FONT-FAMILY:KAITI_GB2312;FONT-SIZE:18PX;" ...</span> after > Business processing
<span style= "FONT-FAMILY:KAITI_GB2312;FONT-SIZE:18PX;" > Business process before ... Query Method ...</span>
<span style= "FONT-FAMILY:KAITI_GB2312;FONT-SIZE:18PX;" ...</span> after > Business processing
OK, so far our static proxy implementation, but the problem is followed, the observation code can be found that each proxy class can only be an interface service, a Accountproxy class implementation of an account interface, then if I have more than one interface, is not to write more than one proxy class corresponding to it. In this way the development of the program will inevitably generate an excessive number of agents, and all the agent operation in addition to the method called, the other operations are the same, then it must be duplicated code. The best way to solve this problem is to complete the proxy function through a proxy class, then introduce our dynamic agent.




Talk about the proxy pattern of Java to know a

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.