Java design mode--proxy mode

Source: Internet
Author: User

Proxy mode proxies: to provide a proxy for other objects and to control access to the object, like the relationship between the broker and the star, the broker is the star's proxy class. The simple thing is to do the processing before and after the method call, AOP idea, the advantage is not to change the original class method on the basis of dynamic add other methods.

3 Roles for proxy mode

1. Abstract role 2. Real role

3. Proxy roles

1. Static Proxy

The proxy class invokes the method of the proxy class.

2. Dynamic Agent---More commonly used

 Public Interface people {            void  eat ();    }
 Public class Implements people {    publicvoid  eat () {        System.out.println ("eat");}    }

Proxy class---Need to implement Invocationhandler interface

 Public classPorxyhandlerImplementsInvocationhandler {People people=NULL;  PublicPorxyhandler (People people) { This. People =people; }     Publicobject Invoke (Object proxy, Method method, object[] args)throwsThrowable { This. before ();        Method.invoke (people, args);  This. After (); return NULL; }        Private voidbefore () {System.out.println (Wash); }        Private voidAfter () {System.out.println ("Wash the dishes"); }}
 Public class Client {        publicstaticvoid  main (string[] args) {        new Class[]{people.  Classnew Proxyhandler (new  Zhangsan ()));        People.eat ();            }}

Java design mode--proxy 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.