码迷,mamicode.com
首页 > 其他好文 > 详细

代理模式

时间:2020-09-15 21:27:15      阅读:50      评论:0      收藏:0      [点我收藏+]

标签:hand   动态   span   ice   main   lang   and   string   getname   

一、动态代理

  1、定义接口

public interface CoverProxyInterface {
    String eat(String str);

    String sleep(String str);
}

  2、实现接口

public class CoverProxyClass implements CoverProxyInterface {
    @Override
    public String eat(String str) {
        return str;
    }

    @Override
    public String sleep(String str) {
        return str;
    }
}

  3、实现代理

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class ProxyPractice {
    public static void main(String[] args) {
        CoverProxyInterface cpc = new CoverProxyClass();

        CoverProxyInterface proxy = (CoverProxyInterface) Proxy.newProxyInstance(cpc.getClass().getClassLoader(), cpc.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                if ("eat".equals(method.getName())) {
                    args[0] = "" + args[0];
                    String res = (String) method.invoke(cpc, args);
                    res = res + " 大西瓜";
                    return res;
                } else if ("sleep".equals(method.getName())) {
                    args[0] = "" + args[0];
                    String res = (String) method.invoke(cpc, args);
                    res = res + " 大软床";
                    return res;
                } else {
                    return null;
                }
            }
        });

        String eat = proxy.eat("");
        System.out.println(eat);
        String sleep = proxy.sleep("");
        System.out.println(sleep);
    }
}

 

代理模式

标签:hand   动态   span   ice   main   lang   and   string   getname   

原文地址:https://www.cnblogs.com/linding/p/13601116.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!