zoukankan      html  css  js  c++  java
  • 代理模式之动态代理

    import java.lang.reflect.InvocationHandler;
    import java.lang.reflect.Method;
    import java.lang.reflect.Proxy;
    
    
    //接口
    interface MyInterface {
    	public void action();
    }
    
    // 被代理类
    class MyObject implements MyInterface {
    	@Override
    	public void action() {
    		System.out.println("我是被代理类,运行action!

    "); } } //被代理接口 interface ClothFactory{ public void productCloth(); } //被代理类 class NikeClothFactory implements ClothFactory{ @Override public void productCloth() { System.out.println("我是被代理类,Nike 生产衣服"); } } //实现InvocationHandler接口的子类 class MyInvocationhandler implements InvocationHandler { private Object obj; public void setObject(Object obj) { this.obj = obj; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("动态代理类运行,收代理费"); Object returnVal = method.invoke(obj, args); return returnVal; } } //动态代理类 class MyProxy { public static Object getProxyInstance(Object obj, InvocationHandler handler) { return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj .getClass().getInterfaces(), handler); } } public class TestProxy { /** * @Title: main * @Description: * @param: * @return void * @user: wangzg * @Date:2014-10-27 * @throws */ public static void main(String[] args) { // TODO Auto-generated method stub //被代理类 MyObject myObject = new MyObject(); MyInvocationhandler myInvocationhandler = new MyInvocationhandler(); myInvocationhandler.setObject(myObject); Object myProxy = MyProxy.getProxyInstance(myObject, myInvocationhandler); MyInterface myInterface = (MyInterface)myProxy; myInterface.action(); NikeClothFactory nikeClothFactory = new NikeClothFactory(); myInvocationhandler.setObject(nikeClothFactory); Object myProxyNike = MyProxy.getProxyInstance(nikeClothFactory, myInvocationhandler); ClothFactory clothFactory = (ClothFactory)myProxyNike; clothFactory.productCloth(); } }


  • 相关阅读:
    excel的支持——xlrd模块、xlwt模块的安装
    安装wxpython——python程序GUI图形界面使用
    if __name__ == '__main__':
    U盘装win7
    cgitb.enable()浏览器报告错误,容易定位问题
    python_study_9-生成式
    python_study_10-单例模式
    python_自动化_1-读取excel
    python_study_8-字符串/列表/字典使用方法
    python_study_7-异常处理
  • 原文地址:https://www.cnblogs.com/liguangsunls/p/6807593.html
Copyright © 2011-2022 走看看