桥接模式《设计模式》

来源:互联网 发布:中邮网络培训学院登录 编辑:程序博客网 时间:2024/05/22 11:43

题目:试想一下,你开一家餐馆,菜的类别。分为肉类,青菜类,汤类,然后不同的类别都有大份儿中份儿小份儿。现在客户端需要计算需要根据客人点的餐算出可人所需要付的金额。 给大家三分钟的思考时间。

。。。

好了,时间到了,面对题目我们首先的想法,估计很多都是这样的
这里写图片描述
我们可以看到大家大概会设计出类似这种的类。同理青菜类 以及汤类。
但是试想一下,如果这个时候,客户说由于客人觉得大分量的还是分量不是很足,这个时候需要添加超大份儿的类别。这个时候我们需要在三个地方分别添加一个超大类别的类。如果开发出了一个新的产品类别,则这个产品类别也要重复添加4份额种类。这样虽然也是符合开闭的设计原则,但是代码的重用性特别的不好。
所以这个时候如果我们使用桥接模式来解决这个问题,就会比较的合适。(多维度问题才用桥接模式)
这里写图片描述
如图:
如此的设计图,有利于,当我们再加入新的产品种类的时候,例如添加超大份儿的时候则只需要在volumnType的子类中完成添加就行了,不用给每个foodType添加了。如果需要添加foodType则只需要添加一个类新的事物类别就行了,也不需要给新的食物类别添加VolumeType 。

好的现在大家思考这样的一个问题,我们根据现在的设计图,是使用继承完成这个题目还是使用组合完成这个题目呢。三分钟。

。。。

好的时间到。
我们知道在设计原则中有一个叫做,favor composition than inheritance .
好了下面是代码的书写时间。

public interface FoodType{    abstract double getPrice();}public interface VolumeType{    // 0 small 1 middle 2 big    public int abstract getVolumeNumber();}public class Big implements VolumnType{    public int getVolumeNumber(){        // this is will provide accordingly         return volumePrice;    }}// the same with middle and small public class Meat implements FoodType{    private VolumeType volType;    // init volType in contructor    // <warning>the VolumeType will passing in as needed by the client .     //and when we are designing an program we should keep in mind what the     //client will off what i can do to make it the client convenient as much as possible <warning>    public Meat(VolumeType type){        volType = type;    }    public double getPrice(){        return meatPrice * volType.getVolumeNumber();    }}// the same as Vegetable and soup .

总结:
桥接模式是解决多维度分类的常见方式。

0 0
原创粉丝点击