• 【c++设计模式】桥接模式


    结构型模式

    7)桥接模式

    桥接模式在适配器模式上做了一定的扩展。
    桥接是计算机网络中的用语,本意是指通过网桥把两个局域网连接在一起。
    假如同时有A和B两个抽象类,在A中包含了B的指针,那么就好像把A和B两个类结合在了一起,于是叫做桥接模式。
    例如葡萄,可以有青葡萄,紫葡萄,而酒可以有低度数酒,高度数酒。把两个类结合在一起,就可以组成各种葡萄酒。

    class Grape{
    public:
        Grape():p_color(""),p_area(""){}
        
        void setColor(string color){
            p_color = color;
        }
        void setArea(string area){
            p_area = area;
        }
        virtual void show(){
            cout<<p_color<<" grape from "<<p_area;
        }
    protected:
        string p_color; //颜色
        string p_area; //产地
    };
    
    class PurpleGrape:public Grape{
    public:
        PurpleGrape(string area):Grape(){
            setColor("purple");
            setArea(area);
        }
    };
    
    class GreenGrape: public Grape{
    public:
        GreenGrape(string area):Grape(){
            setColor("Green");
            setArea(area);
        }
    };
    
    class Alcohol{
    public:
        Alcohol(Grape* g):m_grape(g){}
        virtual void show() = 0;
    protected:
        Grape* m_grape;
        
    };
    
    class Wine : public Alcohol{
    public:
        Wine(Grape* p):Alcohol(p){}
        void show(){
            cout<<"wine is made of ";
            m_grape->show();
            cout<<endl;
        }
    };
    
    class Champagne : public Alcohol{
    public:
        Champagne(Grape* p):Alcohol(p){}
        void show(){
            cout<<"Champagne is made of ";
            m_grape->show();
            cout<<endl;
        }
    };
    
    int main(){
        Grape* g1 = new PurpleGrape("Bordeau");
        Grape* g2 = new GreenGrape("Loire");
        
        Alcohol* a1 = new Wine(g1); //将两个类结合在一起
        Alcohol* a2 = new Champagne(g2); //将两个类结合在一起
        
        a1->show();
        a2->show();
    }
    
  • 相关阅读:
    sql 查询重复数据 删除重复数据
    echarts 仪表板指针点击事件
    Java调用webservice 天气预报
    性能优化高手 一站通关从设计到交付的性能问题
    element-ui 添加空白表格
    Linux文件管理
    Linux第五周
    Linux第四周
    Linux第三周
    Linux第二周
  • 原文地址:https://www.cnblogs.com/corineru/p/12013401.html
Copyright © 2020-2023  润新知