2. Dynamic Agent Action
Finally, learning AOP (aspect-oriented programming), which is a bit like decorator mode, is more flexible than decorator mode!
Invocationhandler
public object invoke (object proxy, Method method, object[] args);
?
When this invoke () method is called!
1. When the proxy object is created? Wrong!
2. When invoking a method in an interface implemented by a proxy object? Right!
?
* Object Proxy: The current object, that is, the object being proxied! In calling who's Method!
* Method: Methods currently being called (method of the target object)
* object[] args: Arguments!
Target object: The object being enhanced
Proxy object: A target object is required and an enhanced object is added to the target object!
Target method: Enhanced Content
Proxy object = target object + Enhanced
?
Instance:
File Description: 1. A waiter interface with the server () method
???? 2. Implements the Manwaiter class of the waiter interface
???? 3. Test.java class
1. Waiter.java interface
// Waiter Public Interface Waiter { ???? // Service ???? Public void serve (); } |
?
2. Manwaiter.java class, implements the waiter interface
? // This class implements the Waiter Interface Public class manwaiter implements Waiter { ???? Public void serve () { ???????? System. out. println (" in the service ..."); ????} } |
?
3. Test.java Test class
/** * what we have to master is the current case! */ Public class Demo2 { ???? @Test ???? Public voidfun1() { ???????? Waiter Manwaiter = new manwaiter (); target Object ???????? /* ???????? * give three parameters to create a method to get the proxy object ???????? */ ???????? ClassLoader Loader = This . GetClass (). getClassLoader (); ???????? Class [] Interfaces = {waiter. class }; ???????? Invocationhandler h = new waiterinvocationhandler (manwaiter); parameter manwaiter represents the target object ???????? // To the proxy object, the proxy object is an object that has been enhanced on the basis of the target object! ???????? Waiter Waiterproxy = (waiter) Proxy. Newproxyinstance(loader, interfaces, h); ???????? ???????? Waiterproxy. Serve (); add " Hello "to the front and add " Goodbye" after " ????} } ? //waiterinvocationhandler realized the Invocationhandler interface, and overrides the The invoke () method inside class Waiterinvocationhandler implements Invocationhandler { ???? Private waiter waiter; target Object ???? ???? // provide constructs a method that assigns a value to a private target object ???? Public waiterinvocationhandler (Waiter waiter) { ???????? This . Waiter = waiter; ????} ???? ???? Public object Invoke (Object proxy, method method, object[] args) ???????????? throws throwable { ???????? System. out. println (" Hello! "); ???????? This . Waiter. Serve (); Call the target method of the target object ???????? System. out. println (" Good bye! "); ???????? returnnull; ????} } |
?
Operation Result:
Dynamic Proxy 2