美文网首页
桥接模式

桥接模式

作者: StevenHD | 来源:发表于2020-11-25 13:15 被阅读0次

    一、桥接模式

    • 解耦
      图解

    示例代码

    #include <iostream>
    
    using namespace std;
    
    class Line
    {
    public:
        virtual void drawLine() = 0;
    };
    
    class Shape
    {
    public:
        Shape(int x, int y, Line * pl = nullptr) : _x(x), _y(y), _pl(pl) {}
        virtual void drawShape() = 0;
    
    protected:
        int _x;
        int _y;
        Line * _pl;
    };
    
    class Circle : public Shape
    {
    public:
        Circle(int x = 0, int y = 0, int radious = 0, Line * pl = nullptr) : Shape(x, y, pl), _radious(radious) {}
    
        void drawShape()
        {
             cout << "draw from" << "(" << _x << ", " << _y << ") " << "radious is " << _radious << endl;
             _pl->drawLine();
        }
    
    protected:
        int _radious;
    
    };
    
    class Rect : public Shape
    {
    public:
        Rect(int x = 0, int y = 0, int len = 0, int wid = 0, Line *pl = nullptr) : Shape(x, y, pl), _len(len), _wid(wid) {}
    
        void drawShape()
        {
             cout << "draw from" << "(" << _x << ", " << _y << ") " << "len is " << _len <<
                     " wid is " << _wid << endl;
             _pl->drawLine();
        }
    
    protected:
        int _len;
        int _wid;
    };
    
    
    class DotLine : public Line
    {
    public:
        void drawLine()
        {
            cout << "Dot Line" << endl;
        }
    };
    
    class SolidLine : public Line
    {
    public:
        void drawLine()
        {
            cout << "Solid Line" << endl;
        }
    };
    
    int main()
    {
        DotLine dl;
        SolidLine sl;
    
        Circle c(1, 2, 3, &dl);
        c.drawShape();
    
        Rect r(1, 2, 3, 4, &sl);
        r.drawShape();
    
    
        return 0;
    }
    

    相关文章

      网友评论

          本文标题:桥接模式

          本文链接:https://www.haomeiwen.com/subject/hkxniktx.html