动态代理&静态代理很好的入门

现业务需求实现:

     直男的小明在遇到任何一个人问候一句 "你吃了吗"。 今天我们经理说了 小明打这个招呼太过于直男 需要在打招呼之前说一下“hello”, 在说完之后我们也要说一下“再见 ”

 我们通过代理的方式对小明打招呼的方式进行增强

先看一下现在的实现(直男版)

public interface HelloInterface {


  void say();
}
public class HelloInterfaceImpl implements HelloInterface {
  @Override
  public void say() {
    System.out.println("你吃了吗 ! ");
  }
}

主函数:

public class HelloMain {


  public static void main(String[] args) {
    HelloInterface helloProxy = new HelloInterfaceImpl();
    helloProxy.say();
  }
}

下面两个代理用到基础类都是基于上面的两个类

一.静态代理

    对HelloInterface接口实现类再次进行包装 ,包装成为静态代理类进行输出。

public class HelloProxy implements  HelloInterface {


  HelloInterface helloInterface = new HelloInterfaceImpl();


  @Override
  public void say() {
    System.out.println("hello");
    helloInterface.say();
    System.out.println("再见");
  }
}

主函数:

public class HelloMain {


  public static void main(String[] args) {
    HelloInterface helloProxy = new HelloProxy();
    helloProxy.say();
  }
}

二:动态代理

1.写一个handler来实现InvocationHandler接口,用于对方法的增强,(程序控制器)

public class ProxyClass implements InvocationHandler {
  //通过构造函数来接受需要增强的接口
  private Object object;


  public ProxyClass(Object o) {
    this.object = o;
  }
  @Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    /**
     method.getName();//得到方法名
     method.getParameterCount();//参数数量
     method.getReturnType();//返回类型
     */
    System.out.println("hello");
    //执行我们的需要增强的接口
    method.invoke(object, args);
    System.out.println("再见!");
    return null;
  }
}

2.主函数:

public class Main {


  public static void main(String[] args) {
    HelloInterface helloInterface = new HelloInterfaceImpl();
    ProxyClass proxy = new ProxyClass(helloInterface);
    //生成动态代理类
    HelloInterface o = (HelloInterface) Proxy.newProxyInstance(helloInterface.getClass().getClassLoader(), helloInterface.getClass().getInterfaces(), proxy);
    o.say();
  }
}

 

三: 动态代理比静态代理优越在哪里?

 哎呀,领导又说小明 下班到招呼的方式也是太尴尬,需要在说“下班了” 之前说一下hello  再见 。 那么我们在上面的基础上再写一下

动态代理的实现很简单 不需要在写这么多的代码

我们只需要在被代理的接口中写一个方法 void seeyou(); 并且在实现类中进行实现。

在主函数生产的动态代理类运行seeyou方法就可以了。

反观静态代理是不是太麻烦了?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值