设计模式-桥接模式

shienh 2020年01月25日 158次浏览

桥接(Bridge)模式的定义如下:将抽象与实现分离,使它们可以独立变化。它是用组合关系代替继承关系来实现,从而降低了抽象和实现这两个可变维度的耦合度。

#include <iostream>
#include <string>
using namespace std;

class MessageImp{
public:
    virtual void PlaySound()=0;
    virtual void DrawShape()=0;
};

class Message{
public:
    Message(MessageImp* msg){
        this->messgerImp = msg;
    }
    virtual void SendMessage()=0;
    virtual void SendPicture()=0;

protected:
    MessageImp* messgerImp;
};

//平台实现n
class PcMessageImp:public MessageImp{
public:
    virtual void PlaySound(){
        cout<<"Pc PlaySound()"<<endl;
    }

    virtual void DrawShape(){
        cout<<"Pc DrawShape()"<<endl;
    }
};

class MobineMessageImp:public MessageImp{
public:
    virtual void PlaySound(){
        cout<<"Mobine PlaySound"<<endl;
    }

    virtual void DrawShape(){
        cout<<"Mobine DrawShape"<<endl;
    }
};

//业务抽象 m
class MessageLite:public Message{
public:
    MessageLite(MessageImp* messgerImp):Message(messgerImp){}
    virtual void SendMessage(){
        messgerImp->DrawShape();
        messgerImp->PlaySound();
    }
    virtual void SendPicture(){
        messgerImp->PlaySound();
    }
};

class MessagePerfect:public Message{
public:
    MessagePerfect(MessageImp* messgerImp):Message(messgerImp){}
    virtual void SendMessage(){
        messgerImp->DrawShape();
    }
    virtual void SendPicture(){
        messgerImp->PlaySound();
    }
};

int main(int argc, char *argv[])
{
    MessageImp* messageImp = new PcMessageImp;
    Message* m = new MessageLite(messageImp);
    m->SendMessage();
    m->SendPicture();
    cout<<endl;
    delete m;
    delete messageImp;

    return 0;
}