前言:关于设计模式的文章,例子全部来自网络,所有选取的文章,都是我见过的写得最好的文章。
The bridge pattern is a design pattern which is meant to "decouple an abstraction from its implementation so that the two can vary independently".The bridge uses encapsulation,aggregation, and can use inheritance to separate responsibilities into different classes.
桥接模式的本质是利用继承实现不同的功能类,然后,不同的“产品”类组合不同的功能类,使得不同“产品”的具有不同的作用。就好比,火箭+ 返回舱 = 航天飞船,火箭+导弹 = 杀伤性武器。
本文以面馆作为例子来讲解桥接模式。例子来源于:http://blog.youkuaiyun.com/xiaoxian8023
一个面馆要做多种不同的面,但是,归其根本,一碗面不外乎由两种原料组成:面和卤。面可以是宽面,窄面,手拉面,刀削面等;卤可以是红烧牛肉,红烧羊肉,酸菜肉丝等。所以,不同的面和不同的卤放在一起,就组成了不同的面。

通过桥接模式,我们可以:[http://blog.youkuaiyun.com/xiaoxian8023]
1. 松散耦合。面条类不再与具体的面类和卤类直接关联,松散了它们之间的耦合;
2. 在变化方面,具体的面条类, 具体的面类和具体的卤类各自的变化,互不影响。
2. 在变化方面,具体的面条类, 具体的面类和具体的卤类各自的变化,互不影响。
3. 满足了开闭原则,不用去修改,只需要添加即可。实例化具体的打卤面时,在客户端指定一下要哪种面,哪个卤即可。
4. 利用聚合组合关系,松散了耦合,使得抽象不再依赖于具体,而具体要依赖于抽象。
4. 利用聚合组合关系,松散了耦合,使得抽象不再依赖于具体,而具体要依赖于抽象。
代码实现:
面类及其子类
abstract class Noodle {
abstract public String getNoodleType();
}
class WideNoodle extends Noodle {
public String getNoodleType() {
return "wide noodle";
}
}
class DaoxiaoNoodle extends Noodle {
public String getNoodleType() {
return "daoxiao noodle";
}
}
卤类及其子类:
abstract class Ingredient {
abstract public String getIngredientType();
}
class BraisedBeef extends Ingredient {
public String getIngredientType() {
return "Braised Beef";
}
}
class BraisedMutton extends Ingredient {
public String getIngredientType() {
return "Braised Mutton";
}
}
面条类及其子类:
abstract class NoodleWithIngredient {
protected Noodle noodle;
protected Ingredient ingredient;
protected String name;
abstract public void Name();
}
class DaoXiaoBraisedBeef extends NoodleWithIngredient {
public DaoXiaoBraisedBeef(String name, Noodle noodle, Ingredient ingredient) {
this.name = name;
this.noodle = noodle;
this.ingredient = ingredient;
}
public void Name() {
System.out.println("Name: " + name + " and the noodle is: " +
noodle.getNoodleType() + " and the ingredient is: " +ingredient.getIngredientType());
}
}
参考:
http://blog.youkuaiyun.com/xiaoxian8023
1471

被折叠的 条评论
为什么被折叠?



