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;
}
相关推荐
Predestination王瀞潞2 小时前
IO操作(Num22)
开发语言·c++
宋恩淇要努力4 小时前
C++继承
开发语言·c++
江公望6 小时前
Qt qmlRegisterSingletonType()函数浅谈
c++·qt
rongqing20197 小时前
Google 智能体设计模式:人机协同(HITL)
设计模式
逆小舟7 小时前
【C/C++】指针
c语言·c++·笔记·学习
江公望7 小时前
Qt QtConcurrent使用入门浅解
c++·qt·qml
我是华为OD~HR~栗栗呀7 小时前
23届考研-Java面经(华为OD)
java·c++·python·华为od·华为·面试
hello_2507 小时前
动手模拟docker网络-bridge模式
网络·docker·桥接模式
爱吃喵的鲤鱼8 小时前
仿mudou——Connection模块(连接管理)
linux·运维·服务器·开发语言·网络·c++
王嘉俊9258 小时前
设计模式--享元模式:优化内存使用的轻量级设计
java·设计模式·享元模式