上一节说到了适配器模式: https://blog.csdn.net/zhanglei082319/article/details/88371572
所谓的适配器模式:是为了应对程序突发情况,而诞生的一种亡羊补牢的补救措施,将类似拯救者对象组合添加到需要补救的对象中,供其临时使用。
今天说一下组合类型的一种新的模式:桥接模式
还是从手机生产这个话题来说,我们知道手机生产所需要的零件有很多,而且有许多零件都是代理商生产的,每个零件都是独立的一个小产品,在经过手机生产商的综合,最后才能生产出手机来。
那么这样的,将不同的一个个零件产品组合到一起,这样的一个过程我们软件领域里可以称之为--->桥接
比如手机需要以下零件,手机壳,触摸屏,半导体,电池等
那么代码可以这样写:
public class Platform{
//电池
private Battery battery;
//半导体
private Semiconductor semiconductor;
//手机壳
private MobilePhoneShell mobilePhoneShell;
//触摸屏
private TouchScreen touchScreen;
public Platform(Battery battery,
Semiconductor semiconductor,
MobilePhoneShell mobilePhoneShell,
TouchScreen touchScreen){
this.battery = battery;
this.semiconductor = semiconductor;
this.mobilePhoneShell = mobilePhoneShell;
this.touchScreen = touchScreen;
}
public Phone buildPhone(){
PhoneBuilder builder = new PhoneBuilder()
.buildBat(this.battery)
.buildSem(semiconductor)
.buildPhoneShell(mobilePhoneShell)
.buildScreen(touchScreen);
return builder.buildPhone();
}
}
这样将不同的完全分离的对象结合在一起使用的方式,我们称之为桥接方式
桥接模式使用的场合: 在一个产品存在着各种不同维度的扩展方向时,我们可以使用桥接模式。