1、接口类(抽象角色)
public
interface
IHello {
public void hello(String name);
}
2、接口实现(真实角色)
public void hello(String name);
}
public
class
HelloImpl
implements
IHello {
@Override
public void hello(String name) {
System.out.println( " Hello, " + name);
}
}
@Override
public void hello(String name) {
System.out.println( " Hello, " + name);
}
}
3、代理类实现(代理角色)


import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class HelloProxyImpl implements InvocationHandler {
private Object delegate;
public Object bind(Object delegate) {
this.delegate = delegate;
return Proxy.newProxyInstance(delegate.getClass().getClassLoader(),
delegate.getClass().getInterfaces(), this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
Object result = null;
try {
print("before call" + method);
result = method.invoke(delegate, args);
print("after call" + method);
} catch (Exception e) {
print(e.toString());
}
return result;
}
private void print(String message) {
System.out.println(message);
}
public
class
Demo {
public static void main(String[] args) {
HelloProxyImpl proxy = new HelloProxyImpl();
IHello helloProxy = (IHello) proxy.bind( new HelloImpl());
helloProxy.hello( " Spring " );
}
}
public static void main(String[] args) {
HelloProxyImpl proxy = new HelloProxyImpl();
IHello helloProxy = (IHello) proxy.bind( new HelloImpl());
helloProxy.hello( " Spring " );
}
}