• java 动态代理


    先贴代码 ,有空再写说明

    package com.pattern.structure.proxy;
    
    /**
     * 信息接口
     */
    public interface Message {
    
        public void sendMessage(String value);
    
    }
    package com.pattern.structure.proxy;
    /**
     * 邮箱实现类
     */
    public class EmailMessage implements Message {
    
        @Override
        public void sendMessage(String value) {
            System.out.println(value);
        }
    
    }
    package com.pattern.structure.proxy;
    
    import java.lang.reflect.InvocationHandler;
    import java.lang.reflect.Method;
    import java.lang.reflect.Proxy; 
    
    /**
     * 动态代理
     */
    public class DynamicProxy implements InvocationHandler {
    
        private Object target;
    
        /**
         * 绑定委托对象并返回一个代理类
         * @param target
         * @return
         */
        public Object bind(Object target) {
            this.target = target;
            // 取得代理对象 ,要绑定接口(这是一个缺陷,cglib弥补了这一缺陷)
            return Proxy.newProxyInstance(target.getClass().getClassLoader(),target.getClass().getInterfaces(), this);
        }
    
        @Override
        public Object invoke(Object obj, Method method, Object[] aobj)
                throws Throwable {        
            Object result = null;
            if(checkSendMessage(aobj[0])){
                result = method.invoke(target, aobj);
            }else{
                System.out.println("发送的短信为空,发不出去");
            }        
            return result;
        }    
    
        public boolean checkSendMessage(Object value){
            return value == null ? false : true;
        }
    
    }
    package com.pattern.structure.proxy;
    
    public class Test {
    
        /**
         * @param args
         */
        public static void main(String[] args) {        
            /**************动态代理******************/
            DynamicProxy dynamicProxy =  new DynamicProxy();
            Message emailMessageProxy = (Message)dynamicProxy.bind(new EmailMessage());
            emailMessageProxy.sendMessage(null);
            emailMessageProxy.sendMessage("动态代理成功发送");
        }
    
    }
  • 相关阅读:
    uva 10099(最大生成树+搜索)
    Codeforces Round #218 (Div. 2) 解题报告
    CodeChef December Challenge 2013 解题报告
    Codeforces Round #217 (Div. 2) 解题报告
    uva 1423 (拓扑排序)
    UESTC 1307 windy数(数位DP)
    Codeforces Round #216 (Div. 2) 解题报告
    Codeforces Round #215 (Div. 2) 解题报告
    uva 10047(BFS)
    uva 10369(最小生成树)
  • 原文地址:https://www.cnblogs.com/evilrogue/p/2881593.html
Copyright © 2020-2023  润新知