动态代理设计模式经常使用的有两种实现,一种是JDK自带的动态代理,另外一种就是cglib的动态代理。java
区别:JDK动态代理的被代理对象必定要有接口,经过动态生成接口实现类而后经过组合的方式实如今方法先后do something.设计模式
cglib经过继承的关系来实如今方法先后do something.ide
JDK动态代理的使用:this
1.接口和实现类设计
public interface Service { Integer getSum(Integer a, Integer b); } public class ServiceImpl implements Service { public Integer getSum(Integer a, Integer b) { return a + b; } }
2.代理处理类 须要实现Invocation接口代理
public class MyInvocationHandler implements InvocationHandler { private Object object; public MyInvocationHandler(Object object) { this.object = object; } @Override public Object invoke(Object paramObject, Method paramMethod, Object[] paramArrayOfObject) throws Throwable { System.out.println(paramMethod.getName() + "start......"); Object result = paramMethod.invoke(object, paramArrayOfObject); System.out.println(paramMethod.getName() + "end......"); return result; } }
3.使用
code
public class Test { public static void main(String[] args) { Service service = new ServiceImpl(); MyInvocationHandler handler = new MyInvocationHandler(service); Service proxy = (Service) Proxy.newProxyInstance(service.getClass() .getClassLoader(), service.getClass().getInterfaces(), handler); Integer result = proxy.getSum(1, 2); System.out.println("result is " + result); } }