静态代理-简单使用

静态代理

为了讲明静态代理,这里代码模拟一个网购快递到送达的过程,忽略金钱交易过程。

接口方式

定义一个买家接口

public interface IBuyer {
    void process();
}

一个具体的买家,具有process方法,买家只负责收物件

public class Buyer implements IBuyer {
    public void process() {
        System.out.println("收到快递...");
    }
}

一个代理类(快递公司),实现买家接口,为买家送货上门

public class BuyerProxy implements IBuyer {
    private IBuyer target;

    public void setTarget(IBuyer target) {
        this.target = target;
    }

    @Override
    public void process() {
        try {
            System.out.println("送的路上...");
            System.out.println("即将送达...");
            target.process();
            System.out.println("完成配送...");
        } catch (Exception e) {
            System.out.println("送快递过程出错...");
        }
    }
}

卖家类,收到订单,委托代理(快递公司)去做事情(送快递)

public class Seller {
    @Test
    public void testSave() {
        // 模拟一个买家下单
        IBuyer buyer = new Buyer();
        // 联系快递公司
        BuyerProxy buyerProxy = new BuyerProxy();
        // 把快递交给快递公司
        buyerProxy.setTarget(buyer);
        // 委托快递公司送快递
        buyerProxy.process();
    }
}
结果:
送的路上...
即将送达...
收到物件...
完成配送...

继承方式

一个具体买家

public class Buyer{
    public void process() {
        System.out.println("收到快递...");
    }
}

一个代理类

public class BuyerProxy extends Buyer {
    private Buyer target;

    public void setTarget(Buyer target) {
        this.target = target;
    }

    @Override
    public void process() {
        try {
            System.out.println("送的路上...");
            System.out.println("即将送达...");
            target.process();
            System.out.println("完成配送...");
        } catch (Exception e) {
            System.out.println("送快递过程出错...");
        }
    }
}

卖家

public class Seller {
    @Test
    public void testSave() {
        Buyer buyer = new Buyer();
        BuyerProxy buyerProxy = new BuyerProxy();
        buyerProxy.setTarget(buyer);
        buyerProxy.process();
    }
}
结果:
送的路上...
即将送达...
收到物件...
完成配送...
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值