您的位置:首页 > 其它

结构型模式---代理模式之动态代理自己实现

2014-03-27 11:41 477 查看
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class DynmicProxyMode {

public static void main(String[] args) {
final HelloWorld impl = new HelloWorldImpl();
HelloWorld helloWolrdProxy = (HelloWorld)Proxy.newProxyInstance(
HelloWorld.class.getClassLoader(),
new Class[] { HelloWorld.class }, new InvocationHandler() {

@Override
public Object invoke(Object proxy, Method method,
Object[] args) throws Throwable {
System.out.println("前");
method.invoke(impl, args);
System.out.println("后");
return null;
}

});
helloWolrdProxy.a("a");
System.out.println("============");
helloWolrdProxy.b("b");
}
}

interface HelloWorld {
public abstract void a(String s);

public abstract void b(String s);
}

class HelloWorldImpl implements HelloWorld {

@Override
public void a(String s) {
System.out.println(s);
}

@Override
public void b(String s) {
System.out.println(s);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: