为对象提供一种代理,以控制对这个对象的访问。
代理类中实际维护了一个被代理对象,以致于他可以随意在目标方法前后做点动作。
程序设计中,可以使用代理将一些无关逻辑的代码进行解耦,比如日志打印。
代理模式类图下列代码演示了一部美版iphone到国行iphone的过程
//苹果公司卖手机
public interface Apple {
Double sell();
}
//实现类:内部卖和中国卖
public class AppleSeller implements Apple {
//代表苹果手机出厂价
protected double price = 4000.0;
@Override
public Double sell() {
System.out.println("iphone的出厂价是:" + price + "元");
return price;
}
}
public class ChinaSeller implements Apple {
//中国手机也得从老美那进口
Apple iphone = new AppleSeller();
Double price;
Double tax = 1000.0;
Double xinku = 3000.0;
@Override
public Double sell() {
//拿到商品原价
Double origin = iphone.sell();
/* 加点税,加点利润 */
price = origin + tax + xinku;
System.out.println("国行iphone的价格为:" + price + " 关税:" + tax + " 辛苦费:" + xinku);
return price;
}
}
//测试
public class ProxyTest {
public static void main(String[] args) {
//我有关系,从苹果公司内部直接买
new AppleSeller().sell();
//我有钱,从国行买
new ChinaSeller().sell();
}
}
//结果:
iphone的出厂价是:4000.0元
iphone的出厂价是:4000.0元
国行iphone的价格为:8000.0 关税:1000.0 辛苦费:3000.0
思考:代理类为什么要和被代理类实现同一接口?
如果你单纯的站在实现代理功能这个角度来看,那的确没必要非要实现什么接口,
站在灵活性设计的角度,也就是真实应用中那一定是面向接口编程,
网友评论