浅谈设计模式之六——Bridge模式

先上uml图:

uml解析:桥接模式讲的就是一个解耦的问题,将抽象与实现分离开来,对接口编程,使得RefinedAbstraction对实现依赖,而不是实现依赖于RefinedAbstraction,符合依赖倒置原则。
下面给出可执行代码
Bridge.h

#pragma once
#include <iostream>
using namespace std;

class AbtractionImplement;

class Abtraction
{
public:
    Abtraction(void);
    virtual ~Abtraction(void);

    virtual void operation() =0;
};

class RefinedAbstraction:public Abtraction
{
public:
    RefinedAbstraction(AbtractionImplement &Imp);
    void operation();
private:
    AbtractionImplement & m_Imp;
};

class AbtractionImplement
{
public:
    virtual void operation()=0;

};

class AbtractionImplementA:public AbtractionImplement
{
public:
    void operation();

};

class AbtractionImplementB:public AbtractionImplement
{
public:
    void operation();
};

Bridge.cpp

#include "Abtraction.h"

Abtraction::Abtraction(void)
{
}

Abtraction::~Abtraction(void)
{
}

RefinedAbstraction::RefinedAbstraction(AbtractionImplement &Imp):m_Imp(Imp)
{

}

void RefinedAbstraction::operation()
{
    m_Imp.operation();
}

void AbtractionImplementA::operation()
{
    cout<<"AbtractionImplementA"<<endl;
}

void AbtractionImplementB::operation()
{
    cout<<"AbtractionImplementB"<<endl;
}

main.cpp

#include "Abtraction.h"

int main(int argc,char **argv)
{
    AbtractionImplementA impA;
    Abtraction *f1 = new RefinedAbstraction(impA);
    f1->operation();

    delete f1;
    AbtractionImplementB impB;
    f1 = new RefinedAbstraction(impB);
    f1->operation();

    return 0;
}

执行之后的结果:

相关文章

迭代器模式(Iterator)迭代器模式(Iterator)[Cursor]意图...
高性能IO模型浅析服务器端编程经常需要构造高性能的IO模型,...
策略模式(Strategy)策略模式(Strategy)[Policy]意图:定...
访问者模式(Visitor)访问者模式(Visitor)意图:表示一个...
命令模式(Command)命令模式(Command)[Action/Transactio...
生成器模式(Builder)生成器模式(Builder)意图:将一个对...