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

    一、动态代理

      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);
        }
    }
  • 相关阅读:
    hive+mysql安装
    (转)hive sql 学习笔记(1)
    「CSPS 2020」动物园
    「CSPS 2019」Emiya 家今天的饭
    「CSPS 2020」儒略日
    「CSPS 2019」划分
    poj2251 Dungeon Master 搜索BFS
    poj1080 Human Gene Functions
    poj2349最小生成树prim算法
    hoj1356 Miller_Rabbin算法
  • 原文地址:https://www.cnblogs.com/linding/p/13601116.html
Copyright © 2011-2022 走看看