ڼС
梦回起点
做你害怕做的事,你会发现:不过如此
本站基于WordPress—主题by 设计窝
冀ICP备15003737号
梦回起点
Copyright © 2015-2024 All rights reserved.

桥接模式——大话设计模式读书笔记

最近事情比较多,所以这本书也就没有继续往下看了。今天来看看桥接模式。

桥接模式(Brideg):将抽象部分与它的实现部分分离,使它们都可以独立地变化。

下面是桥接模式的UML图:

桥接模式

下面是C++实现的代码:


/*
 * Copyright (c) 2017 initm.com All rights reserved.
 * 作者: Stupid
 * 描述: 桥接模式
 * 完成时间: 2017-11-19 19:03
*/
#include <QCoreApplication>
#include <iostream>
#include <cstdlib>

class Implementor
{
public:
    virtual void Operation() = 0;
    virtual ~Implementor(){

    }
};

class ConcreteImplementorA: public Implementor
{
public:
    void Operation()override final{
        std::cout << "具体实现A的方法执行" << std::endl;
    }
};

class ConcreteImplementorB: public Implementor
{
public:
    void Operation()override final{
        std::cout << "具体实现B的方法执行" << std::endl;
    }
};

class Abstraction
{
protected:
    Implementor* implementor;

public:
    void SetImplementor(Implementor* implementor){
        this->implementor = implementor;
    }
    virtual void Operation(){
        implementor->Operation();
    }
};

class RefinedAbstraction: public Abstraction
{
public:
    void Operation()override{
        implementor->Operation();
    }
};

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    system("chcp 65001");

    Implementor* imp = nullptr;
    Abstraction* ab = new RefinedAbstraction;
    ab->SetImplementor(imp = new ConcreteImplementorA);
    ab->Operation();
    delete imp;
    ab->SetImplementor(imp = new ConcreteImplementorB);
    ab->Operation();
    delete imp;
    return a.exec();
}

桥接模式名字的由来大概就是像UML图一样像一个桥,真正相关的是抽象类。

2017-11-19
                         
暂无评论

发表回复