今天学习了桥接模式,感觉很受启发。
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;
}
//
代码,测试过,可用。
----------------------