代理模式学习

代理模式学习

采用动态代理

以房东租房为例
  • 首先得定义一个接口
public interface Rent {
    public void rent();
    public void sell();
    public void rise();
}

  • 定义一个房东类实现具体得接口
public class Landlord implements Rent{
    @Override
    public void rent(){
        System.out.println("房东出租房子");
    }
    @Override
    public void sell() {
        System.out.println("房东要卖房子");
    }
    @Override
    public void rise() {
        System.out.println("房东要涨租");
    }
}

接下来是重点,如何通过InvocationHandler这个接口去实现一个代理,这个模板比较通用,可以作为任意对象得代理,只不过我这里

public class ProxyInvocation implements InvocationHandler 
  1. 声明一个对象
private Object object;

2.使用Set方法给对象赋予实体(当然也可以通过构造函数赋予)

public void setObject(Object object) {
    this.object = object;
}

3.获取代理 使用Proxy得newProxyInstance静态方法获取一个代理对象(此对象相当于中介)

//newProxyInstance参数说明
//1– the class loader to define the proxy class
//2 – the list of interfaces for the proxy class to implement
//3 – the invocation handler to dispatch method invocations to
public Object getProxy(){
    return  Proxy.newProxyInstance(this.getClass().getClassLoader(), this.object.getClass().getInterfaces(),this);
}

4.重写invoke函数 实际上就是代理具体方法

@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    System.out.println("执行了"+method.getName()+"方法");
    Object result = method.invoke(object, args);
    return result;
}

最后用户通过代理来实现landlord得方法,并且附加一些代理自由得方法。

public class Test {
    public static void main(String[] args) {
        Landlord landlord = new Landlord();
        ProxyInvocation proxyInvocation = new ProxyInvocation();
        proxyInvocation.setObject(landlord);
        Rent proxy  = (Rent)proxyInvocation.getProxy();
        proxy.rent();
        proxy.sell();
        proxy.rise();
        
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值