您的位置:首页 > 其它

设计模式:代理模式与装饰模式

2016-08-02 18:18 344 查看

1、装饰者模式与代理模式 (静态代理) 

 在日常开发里面,我们经常需要给某个类的方法增加加某些特定的功能。

       例如:有婴儿,婴儿会吃饭和走动,如以下类

package com.scl.designpattern.proxy.dynamic.cglib;

//客户端
public class Client2
{
public static void main(String[] args)
{
HealthHandle h = new HealthHandle();
Child child = (Child) h.getProxyInstance(new Child());
child.eat();
child.breath();
}
}
客户端

   源码Interceptor签名如下

/**
* All generated proxied methods call this method instead of the original method.
* The original method may either be invoked by normal reflection using the Method object,
* or by using the MethodProxy (faster).      官方建议使用MethodProxy对方法进行调用
* @param obj "this", the enhanced object     跟接口代理一样,第一个参数为Enhanced对象实例
* @param method intercepted Method
* @param args argument array; primitive types are wrapped
* @param proxy used to invoke super (non-intercepted method); may be called
* as many times as needed
* @throws Throwable any exception may be thrown; if so, super method will not be invoked
* @return any value compatible with the signature of the proxied method. Method returning void will ignore this value.
* @see MethodProxy
*/
public Object intercept(Object obj, java.lang.reflect.Method method, Object[] args,MethodProxy proxy) throws Throwable;

另外要补充的两点:

1. 方法拦截器对protected修饰的方法可以进行调用

2. 官方推荐在对委托方法进行调用时使用MethodProxy对方法进行调用。这样有两个好处:①官方说速度比较快 ②在intercept内调用委托类方法时不用保存委托对象引用

以上为本次对代理模式的总结,如有错误烦请指出纠正。转载请注明出处。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: