Proxy Mode: Decoupling
Daily development of logs , permissions , transaction processing , and so on.
Implementation principle:
- An abstract target class is an interface, which has a related method name;
- A specific target class to implement the interface and related methods;
- A proxy class that invokes the target concrete class and adds the logic that it needs;
- The client instantiates the proxy class, invoking the method of the proxy class
schematic diagram of proxy mode implementation
Proxy Mode
Proxy mode : Is the common Java design pattern, his characteristic is the proxy class and the delegate class has the same interface, the proxy class is mainly responsible for the delegate class preprocessing the message, filtering the message, forwarding the message to the delegate class, and afterwards processing the message and so on. 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.
The proxy class can be divided into two types according to the agent's creation period.
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.
static proxy modeAs follows:
1. Abstract Target class
publicinterface Subject(){ publicvoidRequest();}
2. Specific target classes
publicclass RealSubject implements Subject(){ publicvoidRequest(){ };}
3. Proxy class
publicclass Proxy (){ private RealSubject realSubject; publicvoidRequest(){ /**附加逻辑**/ realSubject.Request(); /**附加逻辑**/ };}
Dynamic Agent: JDK Dynamic Agent
3 main classes of JDK dynamic proxies:
Proxy: Agent class
invocationhandler: interface
Method: Methods to be called
Taxinterface.java
publicinterface TaxInterface { publicvoiddoTax();}
Tax.java
publicclass Tax implements TaxInterface{ @Override publicvoiddoTax() { System.out.println("进行所得税计算的逻辑处理"); }}
Timeproxy.java
Public class timeproxy implements Invocationhandler{ PrivateObject obj;//Bind proxy object PublicObjectBind(Object obj) { This. obj = obj;returnProxy.newproxyinstance (Obj.getclass (). getClassLoader (), Obj.getclass (). Getinterfaces (), This); }//Implementation Agent @Override PublicObjectInvoke(Object Proxy, Method method, object[] args)throwsthrowable {Object result =NULL;Try{LongStartTime = System.nanotime (); result = Method.invoke (obj, args);LongEndTime = System.nanotime (); System.out.println ("Calculate program Run Time:"+ (endtime-starttime)); }Catch(Exception e) {E.printstacktrace (); }returnResult }}
Client test: Client.java
publicclass Client { publicstaticvoidmain(String[] args) { new TimeProxy(); TaxInterface taxInterface = (TaxInterface)timeProxy.bind(new Tax()); taxInterface.doTax(); }}
The dynamic proxy of the JDK relies on the interface, and if some classes do not implement the interface, then the JDK proxy cannot be used, which will use the cglib dynamic proxy .
cglib Dynamic Agent
The dynamic agent mechanism of JDK can only implement the class of the interface, and the class that cannot implement the interface cannot implement the dynamic proxy of the JDK, the cglib is to implement the proxy for the class, his principle is to generate a subclass for the target class, and overwrite the method implementation enhancement, but because inherit is adopted, Therefore, the final decorated class cannot be proxied.
examples are as follows:
Bookfacadecglib.java
package com.ldw.dao; publicinterface BookFacade { publicvoidaddBook(); }
Bookcadeimpl1.java
package com.ldw.dao.impl; /** * 这个是没有实现接口的实现类 * * @author csu.ldw * */ publicclass BookFacadeImpl1 { publicvoidaddBook() { System.out.println("增加图书的普通方法..."); } }
Bookfacadeproxy.java
PackageCom.ldw.proxy;ImportJava.lang.reflect.Method;ImportNet.sf.cglib.proxy.Enhancer;ImportNet.sf.cglib.proxy.MethodInterceptor;ImportNet.sf.cglib.proxy.MethodProxy;/** * Use cglib dynamic agent * * @author Student * */ Public class bookfacadecglib implements methodinterceptor { PrivateObject Target;/** * Create proxy Object * * @param target * @return * * PublicObjectgetinstance(Object target) { This. target = target; Enhancer enhancer =NewEnhancer (); Enhancer.setsuperclass ( This. Target.getclass ());//callback methodEnhancer.setcallback ( This);//Create proxy object returnEnhancer.create (); }@Override //callback method PublicObjectIntercept(Object obj, method method, object[] args, Methodproxy proxy)throwsThrowable {System.out.println ("things start."); Proxy.invokesuper (obj, args); System.out.println ("The end of things.");return NULL; } }
Testcglib.java
package com.ldw.test; import net.battier.dao.impl.BookFacadeImpl1; import net.battier.proxy.BookFacadeCglib; publicclass TestCglib { publicstaticvoidmain(String[] args) { BookFacadeCglib cglib=new BookFacadeCglib(); BookFacadeImpl1 bookCglib=(BookFacadeImpl1)cglib.getInstance(new BookFacadeImpl1()); bookCglib.addBook(); } }
Application
SPRINGAOP, struts interceptors, log management, and more.
additional
Struts2 's Interceptor is an AOP idea, using proxy mode
In Struts2, One of the most important classes is when a Org.apache.struts2.dispatcher.FilterDispatcher user submits a httpservletrequest request through a browser, the request is intercepted by a filter filterdispatcher in Web. xml The Filterdispatcher filter first asks if Actionmapper needs to invoke an action to process the request, and if Actionmapper decides that a request needs to be invoked, Filterdispatcher the processing of the request to Actionproxy, Actionproxy the action class that needs to be called through the configuration file Struts.xml, and then Actionproxy creates a actioninvocation instance and generic the action, but before the call, Actioninvocation will load ACTI according to the configuration On related intercepter, wait for the action to complete, Actioninvocation is responsible for finding the corresponding result results according to the configuration in Struts.xml.
Design mode (eight) proxy mode-structural type