不够彻底的桥接方式 - 读《设计模式》

本文通过一个具体的C++实现案例,探讨了桥接模式的应用,并对比了Java实现中存在的不足。通过对不同颜色与笔触大小的抽象,展示了如何使用桥接模式来分离抽象与实现,使得系统更加灵活。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

刘伟主编的重点大学专业教才《设计模式》中关于桥接模式的一个例子11.3.1中用Java实现的一个桥接模式,实现的不够精准:

既然采用的桥接模式,除了基类就不需要知道现实部分的类和其定义了。实现部分的接口完全可以Pen这个基类里面去了。要不要“桥”何用。


用C++重写一遍(没办法,至今不懂Java):

class Color
{
public:
    virtual void bepaint (string pentype, string name) = 0;
};

class Pen
{
    Color* _color;
public:
    Pen(Color* color):_color(color){}
    void setcolor(Color* color)
    {
        _color = color;
    }
    void colorBepaint(string pentype,string name)
    {
        if (_color)
            _color->bepaint (pentype, name);
    }
    virtual void draw (string name) = 0;
};

class smallpen : public Pen
{
public:
    smallpen(Color* color): Pen(color){}
    void draw(string name)
    {
        this->colorBepaint ("小号笔画", name);
    }
};

class bigpen : public Pen
{
public:
    bigpen (Color* color) : Pen (color) {}
    void draw (string name)
    {
        this->colorBepaint ("大号笔画", name);
    }
};

class red : public Color
{
public:
    void bepaint (string pentype, string name)
    {
        mdlcout << pentype << "红色" << name << endl;
    }

};

class blue : public Color
{
public:
    void bepaint (string pentype, string name)
    {
        mdlcout << pentype << "蓝色" << name << endl;
    }

};

测试部分在mdl的main函数里:

extern"C" DLLEXPORT int MdlMain
(
int     argc,
char**  argv
)
{
    Color* r = new red;
    Color* b = new blue;

    Pen* bp0 = new bigpen (r);
    Pen* sp0 = new smallpen (r);

    Pen* bp1 = new bigpen (b);
    Pen* sp1 = new smallpen (b);

    bp0->draw ("花朵");
    sp0->draw ("花朵");

    bp1->draw ("蝴蝶");
    sp1->draw ("蝴蝶");

    delete bp0;
    delete sp0;
    delete bp1;
    delete sp1;
    delete r;
    delete b;

    return EXIT_SUCCESS;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值