刘伟主编的重点大学专业教才《设计模式》中关于桥接模式的一个例子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;
}