主要内容:模式动机与定义模式结构与分析模式实例与解析小结√模式动机假设现在有一个M品牌和一个N品牌的手机,它们都有游戏和通讯录两个小软件。该如何设计:使客户端可以任意的调用两个品牌的小软件?方案一:先建立一个父类“手机品牌”,下有“手机品牌M”和“手机品牌N”,每个子类各有“通讯录”和“游戏”子类。类图:方案二:先建立一个父类“手机软件”,下有“游戏”和“通讯录”,每个子类各有“手机品牌M”和“手机品牌N”子类。类图:方案一的代码类的定义:#includeiostreamusingnamespacestd;classCellphone{public:virtualvoidRun()=0;};classCellphoneBrandM:publicCellphone{public:virtualvoidRun(){coutdevelopthecellphonebrand_mendl;}};classCellphoneBrandN:publicCellphone{public:virtualvoidRun(){coutdevelopthecellphonebrand_nendl;}};classCellphoneGame_M:publicCellphoneBrandM{public:virtualvoidRun(){coutrunthecellphone_game_m'sgameendl;}};classCellphoneAddressList_M:publicCellphoneBrandM{public:virtualvoidRun(){coutrunthecellphone_addresslist_m'sgameendl;}};classCellphoneGame_N:publicCellphoneBrandN{public:virtualvoidRun(){coutrunthecellphone_game_n'sgameendl;}};classCellphoneAddressList_N:publicCellphoneBrandN{public:virtualvoidRun(){coutrunthecellphone_addresslist_n'sgameendl;}};主程序:voidmain(){Cellphone*cellm=newCellphoneBrandM();cellm-Run();CellphoneBrandM*brandm1=newCellphoneGame_M();brandm1-Run();CellphoneBrandM*brandm2=newCellphoneAddressList_M();brandm2-Run();Cellphone*celln=newCellphoneBrandN();celln-Run();CellphoneBrandN*brandn1=newCellphoneGame_N();brandn1-Run();CellphoneBrandN*brandn2=newCellphoneAddressList_N();brandn2-Run();}√.模式定义桥接模式(BridgePattern):将抽象部分与它的实现部分分离,使它们都可以独立地变化。它是一种对象结构型模式。1.什么叫抽象与它的实现分离?2.实现是什么意思?√.桥接模式结构:结构图:(聚合)类的定义:#includeiostream#includestring#includevectorusingnamespacestd;classCellphoneSoft//手机软件{public:virtualvoidRun()=0;};classCellphoneGame:publicCellphoneSoft//游戏软件{public:virtualvoidRun(){coutrunthecellphone'sgameendl;}};classCellphoneAddressList:publicCellphoneSoft//通讯录软件{public:virtualvoidRun(){coutrunthecellphone'saddresslistendl;}};classCellphoneBrand//手机品牌{protected:CellphoneSoft*m_soft;/*手机品牌类包含手机软件类的指针,体现为聚合关系*/public:voidSetCellphoneSoft(CellphoneSoft*temp){m_soft=temp;}virtualvoidRun()=0;};classCellphoneBrandM:publicCellphoneBrand//M品牌{public:virtualvoidRun(){m_soft-Run();}};classCellphoneBrandN:publicCellphoneBrand//N品牌{public:virtualvoidRun(){m_soft-Run();}};主程序:intmain(){CellphoneBrand*brand;brand=newCellphoneBrandM();brand-SetCellphoneSoft(newCellphoneGame());brand-Run();brand-SetCellphoneSoft(newCellphoneAddressList());brand-Run();brand=newCellphoneBrandN();brand-SetCellphoneSoft(newCellphoneGame());brand-Run();brand-SetCellphoneSoft(newCellphoneAddressList());brand-Run();return0;}使用桥接设计模式后的代码:√.模式实例与解析√.小结*桥接模式的优点:将实现给予解耦,让它和界面之间不再永久绑定。抽象和实现可以独立扩展,不会影响到对方。对于“具体的抽象类”所做的改变,不会影响到客户。*桥接模式的缺点:桥接模式的缺点增加了复杂度。*桥接模式的用途:适合使用在需要跨越多个平台的图形和窗口系统上当需要用不同的方法改变接口和实现时,你会发现桥接模式很好用。