博客
关于我
Spring 静态代理与 动态代理 【在理解为学习AOP奠定基础】(七)
阅读量:233 次
发布时间:2019-03-01

本文共 2009 字,大约阅读时间需要 6 分钟。

Spring AOP 代理模式学习

代理模式

代理是通知目标对象后创建的对象。从客户端的角度看,代理对象和目标对象是一样的。

静态代理

出租房屋

public interface Rent {     void Renthouse();}

房东类

public class Host implements Rent {    @Override    public void Renthouse() {        System.out.println("房东有一套房子出租!!!");    }}

代理类

public class Proxy implements Rent {    private Host host;        public Proxy(Host host) {        this.host = host;    }        @Override    public void Renthouse() {        host.Renthouse();        Money();        seeHose();        hetong();    }        public void Money() {        System.out.println("中介-收取一定的报酬会");    }        public void seeHose() {        System.out.println("中介-带我看房子。");    }        public void hetong() {        System.out.println("满意的话,签合同!");    }}

测试类

public class client {    public static void main(String[] args) {        Host host = new Host();        Proxy proxy = new Proxy(host);        proxy.Renthouse();    }}

动态代理

动态代理分为三大类:基于接口(JDK动态代理)、基于类(CGLIB动态代理)、Java字节码实现(Javassist)。

动态代理实现案例

public interface Rent {    void Rent();}
public class Host implements Rent {    @Override    public void Rent() {        System.out.println("房东有一整套房子出租!!!");    }}
public class ProxyInvocationHandler implements InvocationHandler {    private Rent rent;    public void setRent(Rent rent) {        this.rent = rent;    }    public Object getProxy() {        return Proxy.newProxyInstance(            this.getClass().getClassLoader(),            rent.getClass().getInterfaces(),            this        );    }    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {        return method.invoke(rent, args);    }}
public class client {    public static void main(String[] args) {        Host host = new Host();        ProxyInvocationHandler pih = new ProxyInvocationHandler();        pih.setRent(host);        Rent proxy = (Rent) pih.getProxy();        proxy.Rent();    }}

动态代理的好处

  • 可以使真实角色的操作更加纯粹,不去关注一些公共的业务。
  • 公共部分交给代理角色,便于集中管理。
  • 公共部分发生扩展的部分也更容易实现。
  • 一个动态代理类可以代理多个类,只要实现了一个接口即可。
  • 通过以上内容,可以看出动态代理在实际应用中的重要性和优势。

    转载地址:http://venv.baihongyu.com/

    你可能感兴趣的文章
    Protobuf - 语法、字段使用规则、注意事项
    查看>>
    protobuf —— 快速上手
    查看>>
    protobuf —— 认识和安装
    查看>>
    Protobuf 三个关键字required、optional、repeated的理解
    查看>>
    ProtoBuf 原理详解
    查看>>
    Protobuf 实例(java)
    查看>>
    ProtoBuf 实际应用(java)
    查看>>
    Protobuf 属性解释
    查看>>
    Protobuf 编译工具转换 Java 类
    查看>>
    protobuf使用详解
    查看>>
    ProtoBuf在使用protoc进行编译时提示: Required fields are not allowed in proto3
    查看>>
    Protobuf学习 - 入门
    查看>>
    protobuf对象与JSON相互转换
    查看>>
    ProtoBuf的介绍以及在Java中使用protobuf将对象进行序列化与反序列化
    查看>>
    protocol学习笔记001---RPC和HTTP协议之间的区别_与各自优势
    查看>>
    protostuff简单应用
    查看>>
    PRover 开源项目教程
    查看>>
    PyTorch-Tutorials【pytorch官方教程中英文详解】- 4 Transforms
    查看>>
    Proxy server 緩存 jsp html
    查看>>
    Proxy 和 Reflect 结合实现代理和拦截( 代码示例 )
    查看>>