劉偉主編的重點大學專業教才《設計模式》中關於橋接模式的一個例子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;
}