桥梁模式

桥梁模式(BridgePattern)也叫做桥接模式,定义为将抽象和实现解耦,使得两者可以独立地变化。

桥梁模式的重点是在“解耦”上。

桥梁模式通用类图


Abstraction

— 定义抽象类的接口。

— 维护一个指向Implementor类型对象的指针。

RefinedAbstraction

— 扩充由Abstraction定义的接口。

Implementor

— 定义实现类的接口,该接口不一定要与Abstraction的接口完全一致;事实上这两个接口可以完全不同。一般来讲,Implementor接口仅提供基本操作,而Abstraction则定义了基于这些基本操作的较高层次的操作。

ConcreteImplementor

— 实现Implementor接口并定义它的具体实现。

 

桥梁模式的优点

抽象和实现分离

    这也是桥梁模式的主要特点,它完全是为了解决继承的缺点而提出的设计模式,该模式下,实现可以不受抽象的约束,不再绑定在一个固定的抽象层次上。

优秀的扩充能力

    可以独立地对Abstraction和Implementor层次结构进行扩充。

实现细节对客户透明

 

举例:

    来自《Head FirstDesign Pattern》,


C++实现

#include <iostream>

using namespace std;
class TV{   //Implementor
public:
    virtual void on()=0;
    virtual void off()=0;
    virtual void tuneChannel(int ch)=0;
    virtual ~TV(){}
};
class RCA:public TV{    //ConcreteImplementor
public:
    void on(){cout<<"RCA powered on"<<endl;}
    void off(){cout<<"RCA powered off"<<endl;}
    void tuneChannel(int ch){
        cout<<"RCA Channel is changed, current channel is "<<ch<<endl;
    }
};

class Sony:public TV{   //ConcreteImplementor
public:
    void on(){cout<<"Sony powered on"<<endl;}
    void off(){cout<<"Sony powered off"<<endl;}
    void tuneChannel(int ch){
        cout<<"Sony Channel is changed, current channel is "<<ch<<endl;
    }
};

class RemoteControl{
protected:
    TV *tv;
public:
    RemoteControl(TV *_tv):tv(_tv){};
    virtual void on(){tv->on();};
    virtual void off(){tv->off();};
    virtual void setChannel(int ch){tv->tuneChannel(ch);}
    virtual ~RemoteControl(){
    }
};

class ConcreteRemote:public RemoteControl{
private:
    int currentState;
public:
    ConcreteRemote(TV *_tv):RemoteControl(_tv){};
    void setStation(int cs){
        currentState=cs;
        setChannel(cs);
    }
    void nextChannel(){setChannel(++currentState);}
    void previousChannel(){setChannel(--currentState);}
};
int main()
{
    RCA *rca = new RCA;
    ConcreteRemote cr(rca);

    cr.on();
    cr.setStation(5);
    cr.nextChannel();
    cr.previousChannel();
    cr.off();
    delete rca;
    Sony *sony = new Sony;
    ConcreteRemote crs(sony);
    crs.on();
    crs.setStation(10);
    crs.nextChannel();
    crs.previousChannel();
    crs.off();
    delete sony;
    return 0;
}

运行结果:




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值