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

    一、java 有三种代理模式

         1.静态代理:继承

         2. jdk动态代理:条件是,被代理对象需要实现接口

            

     public class MyProxy{
    
          public Object target=null;
    
          public Object newProxy(Object target){
                    this.target=target;
                    return  Proxy.newProxyInstance(
                                     target.getClass().getClassLoader(),
                                     target.getClass().getInterfaces(),
                                     new InvocationHandler(){
                                            public Object  invoke(Object target,
                                                                  Method method,
                                                                  Object[] args)throws Throwable{
                                                   System.out.println("wo can do...");
                                                                                                          if(method.getName().equalse("prt1")){
                                                            return  method.invoke(target, args);
                                                   }else{
                                                            return null;
                                                   }
                                            }
                                       }
                                    );
              }
              
    }
    public class Test{
            public static void main(String [] args){
                  MyTarget mt=new MyTarget();
                                  MyProxy mp=new MyProxy();
                                  iDoSomething id=(iDoSomething)mp.newProxy(mt);
                                  id.prt1();
                                  id.prt2();
            }
    }

    3.cglib 动态代理:条件是,被代理对象的类不能用 final 修饰,如果类中的方法有 final  static 修饰时,对该方法无效。

    二、比较代理模式与装饰模式

            相同点:都是根据目标对象创建新对象;都能实现对目标对象的拓展

           不同点:1.jdk动态代理是通过反射动态创建新对象;装饰模式是把目标作为参数传给新对象。

                         2.代理模式除了拓展对象外,更多强调对目标对象的保护和控制权限。

                                 代理权限控制的有趣小故事:追一个女孩,本想先搞定目标的闺蜜;不料闺蜜认为男孩是个富二代,自己拿下他再说。  

                         装饰模式:“我来锦上添花”

  • 相关阅读:
    03 Logistic Regression
    01 Linear Regression with One Variable
    00 Introduction
    virsh使用
    Linux配置输入设备(如停用笔记本键盘)
    linux安装ipconfig等网络工具
    软件工程团队第五次作业
    团队第四次作业
    软件工程团队第三次作业
    软件工程团队第二次作业
  • 原文地址:https://www.cnblogs.com/conserdao/p/7309753.html
Copyright © 2011-2022 走看看