橋接模式(C++實現)

來源:互聯網
上載者:User

標籤:png   表現層   pac   筆記   iostream   分享   一個   技術分享   福士   

  下午無聊,複習了下橋接模式,做下筆記,以後忘記了可以翻翻筆記來看看,畢竟好記性不如爛筆頭。

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

  假如我買了一輛skoda的小轎車,小轎車開了一段時間,現在車上得radio過時了,希望換下radio;再過段時間,上次換得radio又過時了,希望又換更接近潮流的radio。再者,skoda的車開了幾年,想換量普通的福士的小轎車。上面的車和radio的關係,用我們物件導向的編程思想該怎麼解決那?一般我們會想到,使用繼承來實現。如用一個skoda車的類,繼承自不同的radio類,在用一個VW車的類也去繼承不同的radio,這樣做的確可以實現,但是一旦換得radio多了,或者車的類型多了,管理取來就變的比較複雜。這時橋接模式就可以閃亮登場了,將車和radio兩個類獨立出來,使其可以獨立變化。具體如下面UML類圖:

下面是代碼是代碼實現:

#include <iostream>using namespace std;class Radio //表現層{public:    virtual void install()    {        cout<<"Radio::install()"<<endl;    }};class PqRadio : public Radio{public:    virtual void install()    {        cout<<"PqRadio::install()"<<endl;    }};class MqbRadio : public Radio{public:    virtual void install()    {        cout<<"MqbRadio::install()"<<endl;    }};class RowRadio : public Radio{public:    virtual void install()    {        cout<<"RowRadio::install()"<<endl;    }};class Car //實現層{public:    virtual void  configRadio(Radio* radio)    {        cout<<"Car::installRadio()"<<endl;        radio->install();    }};class VwCar : public Car{public:    virtual void configRadio(Radio* radio)    {        cout<<"VwCar::configRadio()"<<endl;        radio->install();    }};class SkodaCar : public Car{public:    virtual void configRadio(Radio* radio)    {        cout<<"SkodaCar::configRadio()"<<endl;        radio->install();    }};int main(int argc, char** argv){    Radio* radioPq = new PqRadio();    Radio* radioMqb = new MqbRadio();    Radio* radioRow = new RowRadio();    Car* car = new SkodaCar();    car->configRadio(radioPq);    car->configRadio(radioRow);    car->configRadio(radioMqb);    delete radioPq;    delete radioMqb;    delete radioRow;    delete car;    return 0;}

輸出結果如下:

  

橋接模式(C++實現)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.