还是一样的需求
需求:
在执行计算的时候,给控制台答应的格式为
begain method with [ args1,args2 ]
end method with result
可以使用动态代理来实现:
定义接口:
package com.dxf.ArithmethicCalculatorProxy;
public interface ArithmethicCalculator {
int add(int a, int b);
int sub(int a, int b);
int sul(int a, int b);
int div(int a, int b);
}
实现类:
这个实现类接没有上一个实现类那么乱了,只有业务代码
package com.dxf.ArithmethicCalculatorProxy;
public class ArithmethicCalculatorimp implements ArithmethicCalculator {
public int add(int a, int b) {
int result = a + b;
return result;
}
public int sub(int a, int b) {
int result = a - b;
return result;
}
public int sul(int a, int b) {
int result = a * b;
return result;
}
public int div(int a, int b) {
int result = a / b;
return result;
}
}
创建获取代理对象类:
package com.dxf.ArithmethicCalculatorProxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Array;
import java.util.Arrays;
public class ArithmethicCalculatorProxy {
// 要代理的对象
private ArithmethicCalculator tager;
public ArithmethicCalculatorProxy(ArithmethicCalculator tager) {
this.tager = tager;
}
// 生成代理对象
public ArithmethicCalculator getArithmethicCalculator() {
ArithmethicCalculator proxy = null;
ClassLoader loader = tager.getClass().getClassLoader();
Class[] interfaces = new Class[] { ArithmethicCalculator.class };
InvocationHandler h = new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("begain add" + method.getName() + " with" + Arrays.asList(args));
Object result = method.invoke(tager, args);
System.out.println("end " + method.getName() + " with " + result);
return result;
}
};
/**
* Proxy.newProxyInstance 需要三个参数 创建代理对象需要的 ClassLoader loader
* 代理对象的类加载处理器 Class<?>[] interfaces 被代理的对象的类型及方法 InvocationHandler h
* 在被代理执代理对象执行的方法交由这个处理器
*
*
*/
proxy = (ArithmethicCalculator) Proxy.newProxyInstance(loader, interfaces, h);
return proxy;
}
}
测试类:
package com.dxf.ArithmethicCalculatorProxy;
public class Main {
public static void main(String[] args) {
// 创建目标对象
ArithmethicCalculator target = new ArithmethicCalculatorimp();
// 通过目标对象获取代理对象
ArithmethicCalculator proxy = new ArithmethicCalculatorProxy(target).getArithmethicCalculator();
System.out.println(proxy.add(1, 2));
}
}
测试结果:
begain addadd with[1, 2]
end add with 3