橋接模式(C++實現)——我們來一起畫個有顏色的圖

橋接模式(bridge pattern)

感覺橋接模式是一種挺靈活的設計模式吧,它可以很好的把各個類串在一起。比如說你走進了一家4S店,準備去買輛跑車。跑車的顏色可以是一個類,跑車的形狀可以是一個類,跑車的品牌也是一個類。你告訴店家你想要一輛流線型的黑色蘭博基尼,店家就會按照你的需求帶你去看車了,你作爲客戶是看不到流線型的黑色蘭博基尼的實現過程,而店家就是你的那個橋,對外直接暴露接口,滿足你要流線型的黑色蘭博基尼的需求。
另外如果你還想多瞭解的話,這裏推薦一篇博文,感覺也解釋的挺好的——設計模式讀書筆記-----橋接模式

UML圖

這裏舉一個畫圖的例子
在這裏插入圖片描述
橋接模式主要解決的是如何把各個細節的類串聯起來,滿足調用者的需求。有點像小時候玩的十字路口遊戲,每走到一個分叉路口,都需要做出你的選擇,不斷地選擇之後最後有了只屬於你的結果,人生大概也是如此吧-_-

代碼實現

bridge.h

#ifndef _BRIDGE_
#define _BRIDGE_

#include <iostream>
#include <string>

using namespace std;

class shape
{
public:
    virtual void draw() = 0;
};

class circle:public shape
{
public:
    void draw()
    {
        cout << "draw circle." << endl;
    }
};

class square:public shape
{
public:
    void draw()
    {
        cout << "draw square." << endl;
    }
};

class color
{
public:
    virtual void fill() = 0;
};

class red:public color
{
public:
    void fill()
    {
        cout << "fill red." << endl;
    }
}; 

class green:public color
{
public:
    void fill()
    {
        cout << "fill green." << endl;
    }
};

class bridge
{
private:
    shape *m_shape;
    color *m_color;

public:
    bridge()
    {
        m_shape = NULL;
        m_color = NULL;
    }
    ~bridge()
    {
        if (m_color != NULL)
            delete m_color;
        if (m_shape != NULL)
            delete m_shape;
    }
    void draw_shape_with_color(string shape_type, string color_type)
    {
        if (m_color != NULL)
        {
            delete m_color;
            m_color = NULL;
        }
        if (m_shape != NULL)
        {
            delete m_shape;
            m_shape = NULL;
        }
        if (shape_type == "circle")
            m_shape = new circle;
        else if (shape_type == "square")
            m_shape = new square;
        else
        {
            cout << "There is no this shape:" << shape_type << endl;
            return;
        }
        if (color_type == "red")
            m_color = new red;
        else if (color_type == "green")
            m_color = new green;
        else
        {
            cout << "There is no this color:" << color_type << endl;
            return;
        }
        m_shape->draw();
        m_color->fill();
        cout << endl;
    }
};

#endif
#include "bridge.h"
#include <iostream>
#include <string>

using namespace std;

int main(int argc, char const *argv[])
{
    bridge bridge_demo;
    bridge_demo.draw_shape_with_color("circle", "red");
    bridge_demo.draw_shape_with_color("circle", "black");
    return 0;
}

結果

在這裏插入圖片描述

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