桥接模式(bridge pattern)
感觉桥接模式是一种挺灵活的设计模式吧,它可以很好的把各个类串在一起。比如说你走进了一家4S店,准备去买辆跑车。跑车的颜色可以是一个类,跑车的形状可以是一个类,跑车的品牌也是一个类。你告诉店家你想要一辆流线型的黑色兰博基尼,店家就会按照你的需求带你去看车了,你作为客户是看不到流线型的黑色兰博基尼的实现过程,而店家就是你的那个桥,对外直接暴露接口,满足你要流线型的黑色兰博基尼的需求。
另外如果你还想多了解的话,这里推荐一篇博文,感觉也解释的挺好的——设计模式读书笔记-----桥接模式
UML图
这里举一个画图的例子
桥接模式主要解决的是如何把各个细节的类串联起来,满足调用者的需求。有点像小时候玩的十字路口游戏,每走到一个分叉路口,都需要做出你的选择,不断地选择之后最后有了只属于你的结果,人生大概也是如此吧-_-
代码实现
bridge.h
#ifndef _BRIDGE_
#define _BRIDGE_
#include <iostream>
#include <string>
using namespace std;
class shape
{
public:
virtual void draw() = 0;
};
class circle:public shape
{
public:
void draw()
{
cout << "draw circle." << endl;
}
};
class square:public shape
{
public:
void draw()
{
cout << "draw square." << endl;
}
};
class color
{
public:
virtual void fill() = 0;
};
class red:public color
{
public:
void fill()
{
cout << "fill red." << endl;
}
};
class green:public color
{
public:
void fill()
{
cout << "fill green." << endl;
}
};
class bridge
{
private:
shape *m_shape;
color *m_color;
public:
bridge()
{
m_shape = NULL;
m_color = NULL;
}
~bridge()
{
if (m_color != NULL)
delete m_color;
if (m_shape != NULL)
delete m_shape;
}
void draw_shape_with_color(string shape_type, string color_type)
{
if (m_color != NULL)
{
delete m_color;
m_color = NULL;
}
if (m_shape != NULL)
{
delete m_shape;
m_shape = NULL;
}
if (shape_type == "circle")
m_shape = new circle;
else if (shape_type == "square")
m_shape = new square;
else
{
cout << "There is no this shape:" << shape_type << endl;
return;
}
if (color_type == "red")
m_color = new red;
else if (color_type == "green")
m_color = new green;
else
{
cout << "There is no this color:" << color_type << endl;
return;
}
m_shape->draw();
m_color->fill();
cout << endl;
}
};
#endif
#include "bridge.h"
#include <iostream>
#include <string>
using namespace std;
int main(int argc, char const *argv[])
{
bridge bridge_demo;
bridge_demo.draw_shape_with_color("circle", "red");
bridge_demo.draw_shape_with_color("circle", "black");
return 0;
}