利用桥接模式封装业务单元变化

模板方法是利用继承来完成切割,当对耦合性要求比较高,无法使用继承的时候,可以
横向切割,也就是使用桥接模式。
我们还是通过上面的关于支付的简单例子可以说明它的原理。
显然,它具备和模版方法相类似的能力,但是不采用继承。
public class Payment{
private double amount;
public double getAmount(){
return amount;
}
public void setAmount(double value){
amount = value;
}
private Implementor imp;
public void setImp(Implementor s){
imp=s;
}
public String goSale(){
String x = "不变的流程一 ";
x += imp.Action(); //可变的流程
x += amount + ", 正在查询库存状态"; //属性和不变的流程二
return x;
}
}
interface Implementor{
public String Action();
}
class CashPayment implements Implementor{
public String Action(){
return "现金支付";
}
}
调用:
public class Test{
public static void main (String[] args){
Payment o=new Payment();
o.setImp(new CashPayment());
o.setAmount(555);
System.out.println(o.goSale());
}
}
假定系统已经投运,用户提出新的需求,要求加上信用卡支付和支票支付,您将怎样处
理呢?
public class CreditPayment implements Implementor{
public String Action(){
return "信用卡支付,联系支付机构";
}
}
class CheckPayment implements Implementor{
public String Action(){
return "支票支付,联系财务部门";
}
}
调用:
public class Test{
public static void main (String[] args){
Payment o=new Payment();
o.setImp(new CashPayment());
o.setAmount(555);
System.out.println(o.goSale());
o.setImp(new CreditPayment());
o.setAmount(555);
System.out.println(o.goSale());
o.setImp(new CheckPayment());
o.setAmount(555);
System.out.println(o.goSale());
}
}
这样就减少了系统的耦合性。而在系统升级的时候,并不需要改变原来的代码。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值