1、接口类(抽象角色)

public interface IHello {
 
public void hello(String name);
}

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

3、代理类实现(代理角色)

 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);
 }

4、使用代理

 

public class Demo {
 
public static void main(String[] args) {
  HelloProxyImpl proxy 
= new HelloProxyImpl();

  IHello helloProxy 
= (IHello) proxy.bind(new HelloImpl());
  helloProxy.hello(
"Spring");
 }
}


相关文章: