现弄一个讨债接口
package cn.itcast.g_dongtaidaili; public interface Taozhai { void taozhai(); }
再弄一个讨债实现类
package cn.itcast.g_dongtaidaili; public class Taozhai_Impl implements Taozhai{ @Override public void taozhai() { System.out.println("把钱还给我~~~"); } }
讨债力度太弱,根本讨不回
所以请讨债公司代理讨债
package cn.itcast.g_dongtaidaili; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import org.junit.Test; public class CompanyProxyTaozhai implements Taozhai { Taozhai_Impl taozhai=new Taozhai_Impl(); @Override public void taozhai() { Taozhai strong_taozhai = (Taozhai) Proxy.newProxyInstance(cn.itcast.g_dongtaidaili.Taozhai_Impl.class.getClassLoader(), new Class[]{cn.itcast.g_dongtaidaili.Taozhai.class}, new InvocationHandler() { @Override public Object invoke(Object obj, Method method, Object[] param) throws Throwable { System.out.println("讨债公司利用恐吓 威胁 暴力殴打 打砸等方式逼债"); method.invoke(taozhai, param); System.out.println("讨债成功,讨债公司分取利益"); return null; } }); strong_taozhai.taozhai(); } }
与装饰者设计模式相同,代理讨债也实现了讨债接口,植入原始讨债对象反射出原始讨债方法并进行增强,返回增强的讨债对象.
实现类
package cn.itcast.g_dongtaidaili; public class DemoTaozhai { public static void main(String[] args) { CompanyProxyTaozhai taozhai=new CompanyProxyTaozhai(); taozhai.taozhai(); } }
结果演示
new Class[]{cn.itcast.g_dongtaidaili.Taozhai.class} 第二个参数是接口数组也可以用taozhai.getClass().getInterfaces() 都是得到接口数组 ,为什么是数组,因为实现类可以实现多个接口
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/7494.html