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 小时前
week1-[循环嵌套]画正方形
数据结构·c++·算法
重启的码农2 小时前
ggml 介绍(4) 计算图 (ggml_cgraph)
c++·人工智能
重启的码农2 小时前
ggml 介绍(5) GGUF 上下文 (gguf_context)
c++·人工智能·神经网络
悠哉清闲3 小时前
C++ #if
c++
饕餮争锋3 小时前
设计模式笔记_行为型_策略模式
笔记·设计模式·策略模式
易元3 小时前
模式组合应用-桥接模式(一)
后端·设计模式
是2的10次方啊3 小时前
🕺 行为型设计模式:对象协作的舞蹈家(中)
设计模式
Hard but lovely3 小时前
C++:stl-> list的模拟实现
开发语言·c++·stl·list
the sun344 小时前
常见的设计模式(2)单例模式
单例模式·设计模式
是2的10次方啊4 小时前
🕺 行为型设计模式:对象协作的舞蹈家(上)
设计模式