**定义:**桥接模式(Bridge Pattern)是一种结构型设计模式,它通过将抽象部分与它的实现部分分离,使它们都可以独立地变化。这种模式主要用于当系统的抽象部分和实现部分需要独立地进行扩展时,使得两者之间的耦合度降低。
代码:
cpp
class Shape
{
public:
virtual void drawShape() = 0;
};
class Rectangle : public Shape
{
public:
virtual void drawShape() override
{
std::cout << " Rectangle Draw" << std::endl;
}
};
class Circle : public Shape
{
public:
virtual void drawShape() override
{
std::cout << " Circle Draw" << std::endl;
}
};
class Color
{
public:
Color(Shape*pShape) : m_pShape(pShape){}
virtual void drawColor() = 0;
protected:
Shape *m_pShape = nullptr;
};
class Red : public Color
{
public:
Red (Shape*pShape) : Color(pShape){}
void drawColor()
{
m_pShape ->drawShape();
}
};
class Blue : public Color
{
public:
Blue (Shape*pShape) : Color(pShape){}
void drawColor()
{
m_pShape ->drawShape();
}
};
int main(int argc, char *argv[])
{
Shape *pShapeObj = new Rectangle ();
Color *pColorObj = new Red (pShapeObj);
pColorObj ->drawColor();
return 0;
}