Agent Mode--the spokesperson of the company

Source: Internet
Author: User

Static proxy

As the scale of business increased, in order to facilitate the management of the two factories, Cheng and his partners set up a company, some not very important business to the salesman on behalf of the company to talk to other companies, if the salesman extraordinary play, but also may be a company to talk about a task outside the business. So the boss small achievements can be a lot easier, small into a free to write code, think this is not agent mode, and then began to write code.

Introduced

In some cases, a client does not want or cannot refer directly to an object, and an indirect reference can be implemented through a proxy. Just as we are now unable to access Google directly, through the proxy to the wall.
The proxy pattern is defined as providing a proxy for other objects to control access to the object. in proxy mode, the agent can also increase his or her actions in lieu of being the agent.


There are several important roles in the proxy mode:
-Abstract object parent class (Subject): Is the common parent of real object classes and proxy classes, so that proxy classes can be used wherever real object classes are used.
-Real object Class (Realsubject): Defines the Real object class represented by the proxy class, the object that actually executes the action.
Proxy: The proxy class contains a reference to the real object class that can manipulate the real object, and the proxy class can add its own actions before or after the client invokes the real object, rather than simply passing the call to the real subject object, like the following code, Company agent additional talk about a single business is acting on their own operations.

Package Scut.designmodel.ProxyPattern;//Company classAbstract  class  Company {    //Company name     PublicString CompanyName;//Company Negotiations     Public Abstract voidNegotiate ();//company contract     Public Abstract voidsign ();}//Cheng company, the real negotiating object, that is, the object of the agent class xiaochengcompany extends  Company {@Override Public voidNegotiate () {System.out.println (CompanyName +"Negotiating with other companies"); } @Override Public voidSign () {System.out.println (CompanyName +"signed the contract."); }}//Agent of Xiao Cheng company class xiaochengcompanyproxy extends  Company {    PrivateXiaochengcompany Mxiaochengcompany;//Agent-built constructor, set up a company instance, give the company name information to it     PublicXiaochengcompanyproxy (String CompanyName) {Mxiaochengcompany =NewXiaochengcompany ();    Mxiaochengcompany.companyname = CompanyName; } @Override Public voidNegotiate () {mxiaochengcompany.negotiate ();    Extrabusiness (); } @Override Public voidSign () {mxiaochengcompany.sign (); }//Agent for additional actions     Public voidExtrabusiness () {System.out.println ("The agent has made an extra deal for a single business."); }}//use of agents and other companies to negotiate the signing process Public  class proxypattern {     Public Static voidMain (string[] arg) {Xiaochengcompanyproxy Mxiaochengcompanyproxy =NewXiaochengcompanyproxy ("Xiao Cheng's Company");        Mxiaochengcompanyproxy.negotiate ();    Mxiaochengcompanyproxy.sign (); }}

Operation Result:

小成的公司正在与其他公司谈判代理额外谈好了一单生意小成的公司签好了合约
Application Scenarios
    • When you need to provide a local representation of an object in a different address space. remote agents enable clients to access objects on remote machines, and remote machines may have better computational performance and processing speed, and can quickly respond to and process client requests.
    • When you need to create objects with very high overhead. virtual agents can represent a large object by using a small object, which can reduce the consumption of system resources, optimize the system and improve the speed of operation.
    • When you need to control access to the original object. the protection agent can control access to real objects.
    • When you need to know some additional actions when accessing an object. For example, the number of times an actual object is accessed through a proxy object.
Advantages
    1. The proxy mode can coordinate the caller and the callee, and reduce the coupling degree of the system to some extent.
    2. Remote agents enable clients to access objects on remote machines, and remote machines may have better computational performance and processing speed, and can quickly respond to and process client requests.
    3. Virtual agents represent a large object by using a small object, which can reduce the consumption of system resources, optimize the system and improve the speed of operation.
    4. The protection agent can control access to real objects.

Disadvantages
    1. The static proxy class and the delegate class implement the same interface, and the static proxy class implements the same method through the delegate class. There is a lot of code duplication. If an interface adds a method, all proxy classes need to implement this method in addition to all implementation classes that need to implement this method. Increases the complexity of code maintenance.
    2. Static proxy objects serve only one type of object, if you want to serve multiple types of objects. It is bound to be a proxy for each object, static agent in the program is a little larger than the capacity of the.
Dynamic Agent

Although the company has just been established, but also set up a variety of departments in charge of business. Some departments are very short, such as product department and advertising department need manpower, and then will entrust personnel to recruit, personnel is their agent. Small into the first to use static proxy mode to implement such code, but static proxy objects only serve a department, if you want to proxy another department to write again, then why not write a proxy for all departments? So small achievements from the Internet to find the dynamic proxy mode.

Introduced

The dynamic proxy mode solves the disadvantage of the static agent to implement the agent manually, only by implementing the Invocationhandler interface of the proxy class, the method of the proxy class can be automatically invoked by the Method.invoke method based on the Java reflection mechanism. No manual implementation is necessary.
Dynamic proxies are more flexible because they do not have to specify a proxy class to proxy the proxy object when we design the implementation, and we can defer this designation until the runtime is implemented by the JVM. Instead of explicitly letting it implement the same interface as the Real object class (Realsubject) When designing the Dynamic proxy class (Dynamicproxy), we defer this implementation to runtime.

You can look at the following code:

Dynamic proxy classes:
In order for the Personneldepartment class to be able to implement a series of interfaces implemented by the real object class at runtime, and to perform the related method operations in the interface, You need to have the Dynamicproxy class implement the Java.lang.reflect.InvocationHandler interface that comes with the JDK.

 PackageScut.designmodel.DynamicProxyPattern;ImportJava.lang.reflect.InvocationHandler;ImportJava.lang.reflect.Method;ImportJava.lang.reflect.Proxy; Public  class personneldepartment implements Invocationhandler {    //proxy object    PrivateObject Proxyobject;The Invoke method is executed when a binding relationship, that is, which interface (binding to a specific implementation class) is associated to which method will be invoked.      PublicObjectnewproxyinstance(Object proxyobject) { This. Proxyobject =proxyobject;//This method is used to generate a dynamic proxy class instance for a specified class loader, a set of interfaces, and a calling processor        The first parameter specifies the class loader that produces the proxy object, which needs to be specified as the same class loader as the target object        ///The second parameter implements the same interface as the target object, so only the implementation interface of the target object needs to be obtained.        The third parameter indicates which Invocationhandler invoke method the intercepted method needs to execute when it is intercepted.        //Returns a proxy object based on the incoming target        returnProxy.newproxyinstance (Proxyobject.getclass (). getClassLoader (), Proxyobject.getclass (). GetInterfaces (), This); }@Override    //The method associated with this implementation class is invoked when it is executed    //invocationhandler The method of the interface, proxy represents the agent, method represents the methods that the original object was called, and the args represents the parameters of the method     PublicObjectInvoke(Object Proxy, Method method, object[] args)throwsThrowable {System.out.println ("Personnel preparation Site"); Object result=NULL;Switch(Method.getname ()) { Case "Negotiate":Try{/ * The agent's action before the original object method call * /System.out.println ("HR invites candidates for interview negotiations");//Using the Java reflection mechanism to invoke the target methodresult = Method.invoke (proxyobject, args);/ * Agent action after the original object method call * /System.out.println ("Successful negotiation, personnel development contract"); }Catch(Exception e)                {E.printstacktrace (); System.out.println ("negotiation failed.");ThrowE } Break; Case "Sign":Try{//The agent's action before the original object method callSystem.out.println ("HR invites candidates to sign up for interview");//Using the Java reflection mechanism to invoke the target methodresult = Method.invoke (proxyobject, args);//Agent action after the original object method callSystem.out.println ("Successful signing, personnel department to arrange new colleagues to work"); }Catch(Exception e)                    {E.printstacktrace (); System.out.println ("Signing failed");ThrowE } Break; } System.out.println ("----------------");returnResult }}

Actual class:

Package Scut.designmodel.DynamicProxyPattern;//Department category interface Department {    //Department negotiations     Public  voidNegotiate ();//Department contract     Public  voidsign ();}//Advertising department, the real negotiating object, that is, the object of the agent class advertisingdepartment implements Department {@Override Public voidNegotiate () {System.out.println ("The advertising department is negotiating with the candidates."); } @Override Public voidSign () {SYSTEM.OUT.PRINTLN ("The advertising department and the candidate signed the contract."); }}//Product division, the real negotiating object, that is, the object of the agent class productdepartment implements Department {@Override Public voidNegotiate () {System.out.println ("Product department is negotiating with candidates"); } @Override Public voidSign () {SYSTEM.OUT.PRINTLN ("The product department and the applicant signed the contract."); }}//HR Dynamic Agent recruitment workflow in two departments Public  class dynamicproxypattern {     Public Static voidMain (string[] arg) {personneldepartment personneldepartment =NewPersonneldepartment (); Department madvertisingdepartment = (Department) personneldepartment.newproxyinstance (NewAdvertisingdepartment ());        Madvertisingdepartment.negotiate ();        Madvertisingdepartment.sign (); Department mproductdepartment = (Department) personneldepartment.newproxyinstance (NewProductdepartment ());        Mproductdepartment.negotiate ();    Mproductdepartment.sign (); }}

Results:

人事部准备场地人事部邀请应聘者面试谈判广告部正在和应聘者谈判谈判成功,人事部制定合同1. ----------------人事部准备场地人事部邀请应聘者面试签约广告部和应聘者签好了合约签约成功,人事部安排新同事上班----------------人事部准备场地人事部邀请应聘者面试谈判产品部正在和应聘者谈判谈判成功,人事部制定合同----------------人事部准备场地人事部邀请应聘者面试签约产品部和应聘者签好了合约签约成功,人事部安排新同事上班----------------
Application situations

Dynamic proxy mode is similar to the static proxy, but if the static agent to proxy more objects, it is recommended to use dynamic proxy, you can reduce a lot of duplicate code.

Advantages
    1. Just one dynamic proxy class is needed to solve the hassle of creating multiple static proxies, avoiding the need to repeatedly duplicate redundant code.
    2. When the target code is called, the real class object is invoked dynamically at the time of the method's runtime, and is more flexible without having to instantiate it beforehand.
Disadvantages
    1. Compared to the direct invocation of the static proxy is the proxy class object, the dynamic proxy to pass the reflection, so the efficiency is reduced a little.
    2. The dynamic agent mechanism of the JDK can only broker the class that implements the interface, and the class that cannot implement the interface cannot implement the dynamic proxy of the JDK, but can implement the proxy for the class by Cglib.
Reference
    1. Http://blog.csdn.net/hejingyuan6/article/details/36203505#t2
    2. "Design pattern is very simple", Liu Keng Boat, winter and other authoring-Tsinghua University Press, 2013.7

Agent Mode--the spokesperson of the company

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.