发表于: 2017-10-06 00:00:30

2 726


今天完成的事情:

1 代理的概念:

在不修改原来类的前提下,扩展功能。

原始功能:加减乘除。

新增:计算完后,输出耗时。

原始代码:

public class Math {

public int add(int n1, int n2) {

int result = n1 + n2;

System.out.println(n1 + "+" + n2 + "=" + result);

return result;

}


。。。


使用代理的概念设计,增加一个接口类

public interface IMath {

int add(int n1, int n2);

int sub(int n1, int n2);

int mut(int n1, int n2);

int div(int n1, int n2);

}


一个代理类

public class MathProxy2 implements InvocationHandler {

Object obj1;

public Object getProxyObject(Object obj) {

this.obj1 = obj;

return Proxy.newProxyInstance(

obj1.getClass().getClassLoader(),//类加载

obj1.getClass().getInterfaces(), //获得被代理的对象的所有接口

this);//InvocationHandler对象,为invoke提供执行对象

}

/**

* proxy 被代理的对象

* menthod 被反射的方法

* args 方法的参数

*/

@Override

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

long start = System.currentTimeMillis();

lazy();

Object result = method.invoke(obj1, args);

long span = System.currentTimeMillis() - start;

System.out.println("共用时:" + span);

return result;

}

//延时

private void lazy() {

int n =new Random().nextInt(500);

try {

Thread.sleep(n);

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}


测试类

public class Test2 {

/**

* java动态代理测试

*/

IMath math = (IMath) new MathProxy2().getProxyObject(new Math());

@org.junit.Test

public void test1() {

int n1 = 100, n2 =5;

math.add(n1, n2);

math.sub(n1, n2);

math.mut(n1, n2);

math.div(n1, n2);

}

}



结果



明天计划的事情:


遇到的问题:


收获:

学习了代理的方式,完成需求的增加


返回列表 返回列表
评论

    分享到