First look at the proxy mode, this should be the simplest design pattern of a, class diagram
The most characteristic of the agent mode is that the proxy class and the actual business class implement the same interface (or inherit the same parent class), the proxy object holds a reference to the actual object, while the external invocation is the proxy object, and the actual object's operation is invoked in the internal implementation of the proxy object.
Java dynamic Proxy is actually implemented through the Java reflection mechanism, that is, a known object, and then dynamically call its methods at run time, so that before and after the call to do some corresponding processing, this is more general, give a simple example
For example, we have such a requirement in the application to do a log operation before and after the invocation of a method of a class.
An ordinary interface.
[Java] view plain copy print? Public interface Appservice {public boolean Createapp (String name); }
The default implementation class for this interface
[Java] view plain copy print? public class Appserviceimpl implements Appservice {public boolean Createapp (String name) {System.out.pri Ntln ("app[" +name+ "] has been created."); return true; } }
Log processor
[Java] View plain copy print? public class loggerinterceptor implements invocationhandler {//Note implement this handler interface private object target;//target object references, which are designed as object types, more versatile public loggerinterceptor (object target) { this.target = target; } public object invoke (Object proxy, method method, object[] arg) throws throwable { system.out.println ("entered " + Target.getclass (). GetName () + "-" +method.getname () + ", with arguments{" +arg[0]+ "}"); object result = method.invoke (TargET, ARG);//Call the target object's method system.out.println (" Before return: "+result"; return result; } }
External call
[Java] View plain copy print? public class main { public static void main ( String[] args) { appservice target = new appserviceimpl ()///Generate target object // Next, create a proxy object AppService proxy = ( Appservice) proxy.newproxyinstance ( target.getclass () getClassLoader (), target.getclass (). GetInterfaces ( ), new loggerinterceptor (target); Proxy.createapp ("Kevin test"); } } In addition, spring AOP can be used.