c++设计模式之桥接模式(拼接组合)

桥接模式:就是进行拼接组装
在这里插入图片描述
应用举例:
1.定义了形状,抽象形状接口,圆,矩形
2.定义了颜色,抽象颜色接口,红色,蓝色
3,怎么桥接,抽象具体形状和具体颜色的组合,蓝色矩形,红色圆

1.形状

#include <iostream>
#include <string>

// 抽象部分:形状接口
class Shape {
public:
    virtual void draw() = 0; // 纯虚函数,需要子类实现
};

// 具体实现:圆形
class Circle : public Shape {
public:
    void draw() override {
        std::cout << "Drawing Circle" << std::endl;
    }
};

// 具体实现:矩形
class Rectangle : public Shape {
public:
    void draw() override {
        std::cout << "Drawing Rectangle" << std::endl;
    }
};

2.颜色

// 抽象部分:颜色接口
class Color {
public:
    virtual void fill() = 0; // 纯虚函数,需要子类实现
};

// 具体实现:红色
class Red : public Color {
public:
    void fill() override {
        std::cout << "Filling with Red color" << std::endl;
    }
};

// 具体实现:蓝色
class Blue : public Color {
public:
    void fill() override {
        std::cout << "Filling with Blue color" << std::endl;
    }
};

3.桥接部分

// 桥接部分:具体形状和具体颜色的组合
class BridgeShape {
protected:
    Shape* shape;
    Color* color;

public:
    BridgeShape(Shape* shape, Color* color) : shape(shape), color(color) {}

    void drawAndFill() {
        shape->draw();
        color->fill();
    }
};

// 具体桥接实现:红色圆形
class RedCircle : public BridgeShape {
public:
    RedCircle() : BridgeShape(new Circle(), new Red()) {}
};

// 具体桥接实现:蓝色矩形
class BlueRectangle : public BridgeShape {
public:
    BlueRectangle() : BridgeShape(new Rectangle(), new Blue()) {}
};

运行一下

int main() {
    RedCircle redCircle;
    BlueRectangle blueRectangle;

    redCircle.drawAndFill();
    blueRectangle.drawAndFill();

    return 0;
}

相关推荐

  1. 【前端设计模式模式

    2024-04-24 07:14:02       68 阅读
  2. 设计模式模式

    2024-04-24 07:14:02       44 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-24 07:14:02       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-24 07:14:02       106 阅读
  3. 在Django里面运行非项目文件

    2024-04-24 07:14:02       87 阅读
  4. Python语言-面向对象

    2024-04-24 07:14:02       96 阅读

热门阅读

  1. lucene

    2024-04-24 07:14:02       38 阅读
  2. 浅谈如何学习微信小程序

    2024-04-24 07:14:02       35 阅读
  3. CSS学习

    CSS学习

    2024-04-24 07:14:02      39 阅读
  4. 算法和数据结构4.23:

    2024-04-24 07:14:02       42 阅读
  5. web重点收集

    2024-04-24 07:14:02       137 阅读
  6. 大唐杯模拟题

    2024-04-24 07:14:02       35 阅读
  7. Scala OOP

    2024-04-24 07:14:02       28 阅读
  8. nodejs 中间件

    2024-04-24 07:14:02       38 阅读