Java设计模式-代理模式

来源:互联网 发布:linux init.d不见了 编辑:程序博客网 时间:2024/06/11 06:29

Java设计模式-代理模式

2016/6/18 18:55:22 seventeenWen

其实学代理模式主要是为了理解Spring的AOP思想,

动态代理模式

动态代理主要涉及Proxy和InvocationHandler两个类,可以通过实现该接口的invoke方法,将横切逻辑和业务逻辑编织在一起,

newProxyInstance()的三个参数

方法作用:动态生成一个对象,这个对象实现类多个接口

Object proxy = Proxy.newProxyInstance(ClassLoader classLoader,Class[] interfaces,InvocationHandler handler);

  1. ClassLoader:类加载器

  2. interfaces:需要实现的接口

  3. handler:调用处理器

简单的Demo

Demo的设定:现在要做的事情是我在每一次数据库的操作前后添加日志信息

先来简单定义一个接口:

A接口:

public interface AService {public void addA();public void deleteA();} 

A的实现类:

public class AServiceImp implements AService{public void addA() {    System.out.println("向A中添加一条数据");}public void deleteA() {    System.out.println("向A中删除一条数据");}}

日志记录类:

public class Log {public void beforeLog(){    System.out.println("操作前-----记录日志");}public void afterLog(){    System.out.println("操作后-----记录日志");}}

Handler类(动态代理的关键类):

public class ProxyService implements InvocationHandler{private Object target;private Log log;public ProxyService(Object target){    this.target=target;}public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {    log =new Log();    log.beforeLog();    Object result =method.invoke(target, args);    log.afterLog();    return result;}}

测试类:

public class RunTest {@Testpublic void Demo(){    AService a =new AServiceImp();    ProxyService handler =new ProxyService(a);    ClassLoader loader = this.getClass().getClassLoader();    Class[] interfaces ={AService.class};    AService proxy =(AService) Proxy.newProxyInstance(loader, interfaces, handler);    proxy.addA();    proxy.deleteA();}}

运行结果:

操作前-----记录日志向A中添加一条数据操作后-----记录日志操作前-----记录日志向A中删除一条数据操作后-----记录日志
0 0