設計模式之——橋接模式

handsetsoft.h

#ifndef HANDSETSOFT_H
#define HANDSETSOFT_H
#include <QtDebug>

class HandsetSoft
{
public:
    HandsetSoft() {}
    virtual void run(){ qDebug() << "請選擇應用"; }
};

class HandsetGame : public HandsetSoft
{
public:
    HandsetGame() {}
    void run(){ qDebug() << "運行手機遊戲";}
};

class HandsetAddressList : public HandsetSoft
{
public:
    HandsetAddressList() {}
    void run(){ qDebug() << "運行手機通訊錄";}
};

#endif // HANDSETSOFT_H

handsetBrand.h

#ifndef HANDSETBRAND_H
#define HANDSETBRAND_H

#include "handsetsoft.h"

class HandsetBrand
{
public:
    HandsetBrand() { m_soft = new HandsetSoft(); }
    void setHandsetSoft(HandsetSoft *soft)
    {
        m_soft = soft;
    }
    virtual void run() = 0;
protected:
    HandsetSoft *m_soft;
};

class HandsetBrandN : public HandsetBrand
{
public:
    HandsetBrandN() {}
    void run()
    {
        m_soft->run();
    }
};

class HandsetBrandM : public HandsetBrand
{
public:
    HandsetBrandM() {}
    void run()
    {
        m_soft->run();
    }
};

#endif // HANDSETBRAND_H

main.cpp

#include <QApplication>
#include "handsetBrand.h"

//橋接模式
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    HandsetBrand *n = new HandsetBrandN();
    HandsetSoft *game = new HandsetGame();
    n->setHandsetSoft(game);
    n->run();

    HandsetSoft *address = new HandsetAddressList();
    n->setHandsetSoft(address);
    n->run();

    return a.exec();
}

橋接模式:將抽象部分與它的實現部分分離,使它們都可以獨立地變化

UML
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章