桥接模式

前言:关于设计模式的文章,例子全部来自网络,所有选取的文章,都是我见过的写得最好的文章。

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. 在变化方面,具体的面条类, 具体的面类和具体的卤类各自的变化,互不影响。
3. 满足了开闭原则,不用去修改,只需要添加即可。实例化具体的打卤面时,在客户端指定一下要哪种面,哪个卤即可。
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
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值