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

前端之家收集整理的这篇文章主要介绍了浅谈设计模式之六——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;
}

执行之后的结果:

原文链接:https://www.f2er.com/javaschema/284807.html

猜你在找的设计模式相关文章