设计模式-深入剖析动态代理模式(3)内部运作机制-通俗代码版

public interface Subject {

//业务操作
public void doSomething(String abc);

}

-----

public class RealSubject implements Subject {


//业务操作
public void doSomething(String str) {
System.out.println("do something!---->" + str);
}


}

----

public class MyInvocationHandler implements InvocationHandler {
//被代理的对象
private Object target = null;
//通过构造函数传递一个对象
public MyInvocationHandler(Object _obj){
this.target = _obj;
}
//代理方法
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
//设置返回值
Object result = null;
//前置通知
this.before();
//执行被代理的方法
result = method.invoke(this.target, args);
//后置通知
this.after();

//返回值
return result;
}

//前置通知
public void before(){
System.out.println("执行before方法");
}

//后置通知
public void after(){
System.out.println("执行after方法");
}


}

----

public class DynamicProxy {
//定义要代理哪个类
private Object obj =null;
//通过构造函数传递被代理对象
public DynamicProxy(Object _obj){
Class c = _obj.getClass();
//生成被代理类的代理类
this.obj = Proxy.newProxyInstance(c.getClassLoader(), c.getInterfaces(), new MyInvocationHandler(_obj));
}
//执行代理类的方法
public Object exec(String methodName,Object...args){
//返回值
Object result = null;
//方法中的参数类型
Class[] c= new Class[args.length];
int i=0;
//获得参数的类型
for(Object o:args){
c[i] = o.getClass();
i++;
}
try {
//根据方法名称和参数类型查找到唯一一个方法
Method method=this.obj.getClass().getMethod(methodName, c);
//执行该方法
result = method.invoke(this.obj, args);
} catch (Exception e) {
e.printStackTrace();
}

return result;
}


}

-----

public class Client {
public static void main(String[] args) {
DynamicProxy proxy = new DynamicProxy(new RealSubject());
String[] str = {"1111"};
proxy.exec("doSomething",str);

}
}


posted @ 2014-09-22 09:43  172257861  阅读(90)  评论(0编辑  收藏  举报