23个设计模式之代理模式(2)动态代理

来源:互联网 发布:办公室有老鼠 知乎 编辑:程序博客网 时间:2024/05/25 15:47
package cn.com.dynamic;

public interface Foo {

void doAction();

}


package cn.com.dynamic;


public class FooImpl implements Foo {


public void doAction() {
System.out.println("this is FollImpl!");
}
}


package cn.com.dynamic;


public class FooImpl2 implements Foo {


public void doAction() {
System.out.println("this is FooImpl2!");
}
}


package cn.com.dynamic;


import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;


public class CommonInvocationHandler implements InvocationHandler{
private Object obj;

public void setObj(Object obj) {
this.obj = obj;
}


public CommonInvocationHandler() {

}

public CommonInvocationHandler(Object obj) {
this.obj = obj;
}


@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
return method.invoke(obj, args);
}
}


package cn.com.dynamic;


import java.lang.reflect.Proxy;


public class ClientDemo {
public static void main(String[] args) {
CommonInvocationHandler comm = new CommonInvocationHandler();
comm.setObj(new FooImpl());


Foo f = null;
f = (Foo) Proxy.newProxyInstance(Foo.class.getClassLoader(),
new Class[] { Foo.class}, comm);
f.doAction();
comm.setObj(new FooImpl2());
System.out.println("----------------------------");
f = (Foo) Proxy.newProxyInstance(Foo.class.getClassLoader(),
new Class[] { Foo.class}, comm);
f.doAction();
}
}

原创粉丝点击