mysql开发网站开发,企业邮箱登录入口手机网页版,平面设计网页设计专员,域名历史解析查询本文章属于专栏《设计模式#xff08;极简c版#xff09;》 继续上一篇《原型模式#xff08;极简c#xff09;》。本章简要说明桥接模式。本文分为模式说明、本质思想、实践建议、代码示例四个部分。
模式说明 方案#xff1a; 将抽象部分与它的实现部分分离#xff0c… 本文章属于专栏《设计模式极简c版》 继续上一篇《原型模式极简c》。本章简要说明桥接模式。本文分为模式说明、本质思想、实践建议、代码示例四个部分。
模式说明 方案 将抽象部分与它的实现部分分离使多个组合在一起的品类可以独立变化。优点 分离抽象和实现部分使得它们可以独立地变化易于扩展。通过对象组合而不是继承的方式实现解耦提高了代码的灵活性。缺点 增加了系统的复杂度因为需要多个抽象类和实现类。本质思想用一个抽象类组合另外一个抽象类如形状和颜色在构建时使用具体的类完成组合如红色的正方形。实践建议一个基础主体包含多个属性时都可以使用。该模式能很好地保留设计时的模块语义方便未来维护
#include iostream// 实现部分接口颜色
class Color {
public:virtual void applyColor() const 0;
};// 具体实现类红色
class RedColor : public Color {
public:void applyColor() const override {std::cout Red std::endl;}
};// 具体实现类绿色
class GreenColor : public Color {
public:void applyColor() const override {std::cout Green std::endl;}
};// 抽象部分类形状
class Shape {
protected:Color* color;public:Shape(Color* c) : color(c) {}virtual void draw() const 0;
};// 扩展的抽象部分类圆形
class Circle : public Shape {
public:Circle(Color* c) : Shape(c) {}void draw() const override {std::cout Drawing Circle with color ;color-applyColor();}
};// 扩展的抽象部分类矩形
class Rectangle : public Shape {
public:Rectangle(Color* c) : Shape(c) {}void draw() const override {std::cout Drawing Rectangle with color ;color-applyColor();}
};int main() {Color* red new RedColor();Color* green new GreenColor();Shape* redCircle new Circle(red);Shape* greenRectangle new Rectangle(green);redCircle-draw(); // 输出: Drawing Circle with color RedgreenRectangle-draw(); // 输出: Drawing Rectangle with color Greendelete red;delete green;delete redCircle;delete greenRectangle;return 0;
}