桥接模式
2020-11-25 本文已影响0人
StevenHD
一、桥接模式
-
解耦
图解
示例代码
#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;
}