静态代理
为了讲明静态代理,这里代码模拟一个网购快递到送达的过程,忽略金钱交易过程。
接口方式
定义一个买家接口
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();
}
}
结果:
送的路上...
即将送达...
收到物件...
完成配送...