About the concept of proxy mode:
With now quite popular US Ma Song event to do metaphor, Bao strong equivalent is the agent class, Song is the proxy class, Song agent Bao Strong many behavior, Song to Bao strong message pretreatment, filtering, forwarding, PR and so on. Just as PR, when Bao Qiang need PR when the strong do not have to really personally to achieve public relations, the real realization is done by the Song agent.
Proxy mode is a common Java design pattern, his characteristic is that the proxy class and the delegate class have the same interface, the proxy class is mainly responsible for the delegate class preprocessing messages, filtering messages, forwarding messages to the delegate class, and post-processing messages. 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.
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: When the program is running, it is created dynamically using the reflection mechanism.
First we use code to explain static proxies:
The following is the Istar type interface, which is the behavior of the star:
1 Public Interface istar{2 // work hard 3 void hardwork; 4 // Love Your wife 5 void Lovewife; 6 }
The following is the implementation class for the Istar interface Satr
public class Star implementsistar{ private String Mname; public Star (String mname) {mname =this .mname; public void hardwork () {System.out.printf ( public void Lovewife () {System.out.printf ( this . mname+ "Love Your Wife"
Brokers represent stars, so in a sense they have the same behavior as stars
Public classAgentImplementsistar{//objects that require a proxyIStar Mistar; //a member variable of the proxy class BooleanMishappy; PublicAgent (IStar IStar) {Mistar=IStar; } PublicAgent (IStar IStar,Booleanishappy) {Mistar=IStar; Mishappy=Ishappy; } //same method as the proxy class Public voidhardwork () {mistar.hardwork;}//at this point, the proxy class can also change the behavior method of the proxy class Public voidLovewife () {if(mishappy) {mistar.lovewife; }Else{System.out.printf ("Broker Revolt"); }} }
Test class
Public class test{ publicstaticvoid main (string[] args) { // Create a new proxy object here is the star Wangbaoqiang Star baoqiang=new star ("Wangbaoqiang"); // tell the broker that he needs a proxy object is the star Wangbaoqiang and the Economic man ishappy attribute set // as false Agent SONGJJ =new Agent (Baoqiang,false); Songjj.hardwrok (); Songjj.lovewife ();}}
Output: Wangbaoqiang hard work
Broker Revolt
The above is an example of a static proxy, which helps to decouple the code.
Next is the dynamic proxy mode:
Requirements are as follows: Use Java code to complete the integer subtraction algorithm, and
1. Track ongoing activities during program execution
2, I hope the calculator can only handle positive arithmetic
For the sake of the centralization of code and not mixing we use dynamic Proxy mode to implement
The first is to create an interface
1 Public InterfaceArithmeticcalculator {2 3 intAddintIintj);4 intSubintIintj);5 6 intMulintIintj);7 intDivintIintj);8 9}
The second is to implement the Arithmeticcalculator interface
Public classArithmeticcalculatorimplImplementsArithmeticcalculator {@Override Public intAddintIintj) {intresult = i +J; returnresult; } @Override Public intSubintIintj) {intresult = i-J; returnresult; } @Override Public intMulintIintj) {intresult = i *J; returnresult; } @Override Public intDivintIintj) {intresult = I/J; returnresult; }}
Dress Up proxy class Arithmeticcalculatorloggingproxy
11 PackageCOM.ATGUIGU.SPRING.AOP;2233ImportJava.lang.reflect.InvocationHandler;44ImportJava.lang.reflect.Method;55ImportJava.lang.reflect.Proxy;66Importjava.util.Arrays;7788 Public classArithmeticcalculatorloggingproxy {99Ten10//the object to be proxied One11Privatearithmeticcalculator Target; A12 -13 PublicArithmeticcalculatorloggingproxy (arithmeticcalculator target) { -14Super(); the15 This. target =Target; -16 } -17 -18//returns the proxy object +19 Publicarithmeticcalculator Getloggingproxy () { -Arithmeticcalculator proxy =NULL; +21st//gets the loader to proxy the object AClassLoader loader =Target.getclass (). getClassLoader (); atThe Class [] interfaces =NewClass[]{arithmeticcalculator.class}; - -Invocationhandler h =NewInvocationhandler () { -25/** - * Proxy: Agent object. This object is not normally used - method: Methods that are being called in * Args: Calling method passed in Parameters - in*/ to30@Override +31 Publicobject Invoke (Object proxy, Method method, object[] args) -32throwsThrowable { theMethodName String =method.getname (); *34//Print Log $System.out.println ("[Before] the method" + MethodName + "begins with" +arrays.aslist (args));Panax Notoginseng36 -37//calling the target method the$ Object result =NULL; +39 A40Try { the41//front-facing notifications +result =Method.invoke (target, args); -43//returns a notification that can access the return value of a method $44}Catch(NullPointerException e) { $45e.printstacktrace (); -46//exception Notification that can access the exception that occurs with the method -47 } the48 -49//Post notification. The return value of the method cannot be accessed because the method can be an exceptionWuyi50 the51//Print Log -System.out.println ("[after] the method ends with" +result); Wu53 -54returnresult; About55 } $56 }; -57 -58/** - Loader: The class loader used by the proxy object. A * Interfaces: Specifies the type of proxy object. That is, what methods can be found in the Proxy proxy object . + H: How to respond when invoking the method of a proxy object, in effect invoking the Invocationhandler Invoke method the +*/ -+ =(arithmeticcalculator) proxy.newproxyinstance (loader, interfaces, h); $64 the65returnproxy; the66 } the67}
Test class
1 PackageCOM.ATGUIGU.SPRING.AOP;2 3 ImportOrg.springframework.context.ApplicationContext;4 ImportOrg.springframework.context.support.ClassPathXmlApplicationContext;5 6 Public classMain {7 8 Public Static voidMain (string[] args) {9Arithmeticcalculator Arithmeticcalculator =NewArithmeticcalculatorimpl ();Ten OneArithmeticcalculator = A NewArithmeticcalculatorloggingproxy (arithmeticcalculator). Getloggingproxy (); - - intresult = Arithmeticcalculator.add (11, 12); theSYSTEM.OUT.PRINTLN ("Result:" +result); - -result = Arithmeticcalculator.div (21, 3); -SYSTEM.OUT.PRINTLN ("Result:" +result); + - } + A}
Java proxy mode