学习设计模式(4)——桥接模式

今天学习了桥接模式,感觉很受启发。


1.桥接模式UML图



2. 理解桥接模式

(1) 将抽象和实现分离开来。

(2) 不同的实现可以自由发展。

(3) 不同的抽象,也可以有许多不同的继承,这些继承可以多种多样。


3. 代码

说明 :

(1) shape是最高抽象,然后你可以自己继承多种形状,圆形,方形,星型,三角形等等。而且就方形而言,方形还可以分为直角边的方形,圆角方形等。多种多样的发展。

(2) 实现部分,就可以多种多样的去发展了。


#include <iostream>

using namespace std;

class DrawingImplementor
{
public:
    virtual void drawSquare(double) = 0;

    virtual ~DrawingImplementor() {}
};

class DrawingImplementorA : public DrawingImplementor
{
public:
    DrawingImplementorA() {}

    virtual ~DrawingImplementorA() {}

    void drawSquare(double side)
    {
        cout << "\nImplementorA.square with side = "<< side << endl;
    }
};

class DrawingImplementorB: public DrawingImplementor
{
public:
    DrawingImplementorB() {}

    virtual ~DrawingImplementorB() {}

    // example: drawing with pencil
    void drawSquare(double side)
    {
        cout << "\nImplementorB.square with side = "<< side << endl;
    }
};

class Shape
{
public:
    virtual void draw() = 0;
    virtual void resize(double pct) = 0;
    virtual ~Shape() {}
};

class Square : public Shape
{
public:
    Square(double s, DrawingImplementor& Implementor) :
        side(s), drawingImplementor(Implementor) {}

    virtual ~Square() {}

    void draw()
    {
        drawingImplementor.drawSquare(side);
    }

    void resize(double pct)
    {
        side *= pct;
    }

private:
    double side;
    DrawingImplementor& drawingImplementor;
};

int main(int argc, char* argv[])
{
    DrawingImplementorA ImplementorA;
    DrawingImplementorB ImplementorB;

    Square sqa(1, ImplementorA);
    Square sqb(2, ImplementorB);

    Shape* shapes[2];
    shapes[0] = &sqa;
    shapes[1] = &sqb;

    shapes[0]->resize(10);
    shapes[0]->draw();
    shapes[1]->resize(10);
    shapes[1]->draw();

    return 0;
}

//




代码,测试过,可用。



----------------------

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值