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;
}
相关推荐
樱木Plus2 天前
深拷贝(Deep Copy)和浅拷贝(Shallow Copy)
c++
willow2 天前
Axios由浅入深
设计模式·axios
blasit4 天前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
七月丶4 天前
别再手动凑 PR 了:这个 AI Skill 会按仓库习惯自动建分支、拆提交、提 PR
人工智能·设计模式·程序员
刀法如飞4 天前
从程序员到架构师:6大编程范式全解析与实践对比
设计模式·系统架构·编程范式
九狼4 天前
Flutter + Riverpod +MVI 架构下的现代状态管理
设计模式
静水流深_沧海一粟5 天前
04 | 别再写几十个参数的构造函数了——建造者模式
设计模式
StarkCoder5 天前
从UIKit到SwiftUI的迁移感悟:数据驱动的革命
设计模式
肆忆_5 天前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++