设计模式_代理模式
代理模式应用场景
比如在企业里面老板有要事现在立马开一个会议,一般来说让老板直接通知各个部门开会是不太可能的,那么老板只需要把这个事情安排给秘书,然后秘书各个部门通知到位,要叮嘱的事情,时间,会议大体内容等通知到位,到点以后老板只在会议室开会就可以,这就是一个典型的代理模式使用场景,其实现跟其他设计模式大同小异,直接上代码看例子,他一般分为动态代理个静态代理
静态代理代码
主题接口
package com.wyw; /** * Created by Administrator on 2017/5/1. */ public interface Subject { public void oprate(); }
主题接口的实现,这里做了两个实现
package com.wyw; /** * Created by Administrator on 2017/5/1. */ public class Save implements Subject { @Override public void oprate() { System.out.println("实现了subject-----save"); } }
package com.wyw; /** * Created by Administrator on 2017/5/1. */ public class Delete implements Subject { @Override public void oprate() { System.out.println("实现了subjecy----deletes"); } }
重点是代理类
package com.wyw; /** * Created by Administrator on 2017/5/1. */ public class Proxy implements Subject { private Subject subject; @Override public void oprate() { System.out.println("代理执行之前"); this.subject.oprate(); System.out.println("代理执行之后"); } public Proxy(Subject subject){ this.subject = subject; } }
测试用例
package com.wyw; /** * Created by Administrator on 2017/5/1. */ public class Test { public static void main(String[] args) { Subject subject = new Delete(); Proxy proxy = new Proxy(subject); proxy.oprate(); } }
静态代理的实现就这么简单,下来介绍动态代理
上代码了
首先来个服务接口
package com.proxy; /** * Created by wuyawei on 2017/5/5. */ public interface Service { public void add(); }
根据套路再来个服务的实现
package com.proxy; /** * Created by wuyawei on 2017/5/5. */ public class ServiceImp implements Service { @Override public void add() { System.out.println("service实现类"); } }
下面是重点,代理类,代理类必须要实现jdk自带的InvocationHandler接口,并且实现它的invoke()方法,还要我们需要自行建立一个获取代理的方法(getProxy()),里面通过反射的获取所有接口对象交给jdk的代理去实现
package com.proxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; /** * Created by wuyawei on 2017/5/5. */ public class InvokeProxy implements InvocationHandler { private Object target; public InvokeProxy(Object target){ this.target = target; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("invoke()执行之前"); Object result = method.invoke(target,args); System.out.println("invoke()执行之后"); return result; } public Object getProxy(){ ClassLoader loader = Thread.currentThread().getContextClassLoader(); Class<?>[] interfaces = target.getClass().getInterfaces(); return Proxy.newProxyInstance(loader,interfaces,this); } }
然后来一段测试代码
package com.proxy; /** * Created by wuyawei on 2017/5/5. */ public class Test { public static void main(String[] args) { Service service = new ServiceImp(); InvokeProxy invokeProxy = new InvokeProxy(service); Service serviceProxy = (Service) invokeProxy.getProxy(); serviceProxy.add(); } }
代理模式具体还没理解,有待进一步深究
具体参见:http://www.cnblogs.com/chinajava/p/5880870.html