模板方法是利用继承来完成切割,当对耦合性要求比较高,无法使用继承的时候,可以
横向切割,也就是使用桥接模式。
我们还是通过上面的关于支付的简单例子可以说明它的原理。
显然,它具备和模版方法相类似的能力,但是不采用继承。
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());
}
}
这样就减少了系统的耦合性。而在系统升级的时候,并不需要改变原来的代码。
利用桥接模式封装业务单元变化
最新推荐文章于 2023-11-21 22:23:15 发布