黑马程序员技术交流社区
标题:
静态代理和动态代理代码对比
[打印本页]
作者:
GXM
时间:
2016-11-2 20:31
标题:
静态代理和动态代理代码对比
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class Test3 {
public static void main(String[] args) {
/*静态代理
* NikeColthFactory cf = new NikeColthFactory();
* MyProxy1 p = newMyProxy1(cf);
* p.produceClothFactory();*/
/*动态代理
NikeColthFactory cf = new NikeColthFactory();
MyProxy2 p2 = new MyProxy2();
Object po = p2.getProxyObject(cf);
clothFactory co = (clothFactory) po;
co.produceClothFactory();*/
}
}
// 被代理类接口
interface clothFactory {
void produceClothFactory();
}
// 被代理类
class NikeColthFactory implements clothFactory {
@Override
public void produceClothFactory() {
System.out.println("Nike工厂");
}
}
// 静态代理
class MyProxy1 implements clothFactory {
clothFactory cf;
public MyProxy1(clothFactory cf) {
this.cf = cf;
}
@Override
public void produceClothFactory() {
System.out.println("开始代理");
cf.produceClothFactory();
}
}
// 动态代理
class MyProxy2 implements InvocationHandler {
Object obj; // 声明 一个被代理类对象
public Object getProxyObject(Object obj) {
this.obj = obj; // 将被代理类对象实例化
// 返回代理类对象
return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj
.getClass().getInterfaces(), this);
}
@Override
// 当通过代理类的对象发起对被重写的方法的调用时,都会转为对如下invoke()方法的调用.
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
Object returnVal = method.invoke(obj, args);
return returnVal;
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2