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

发布于:2024-04-24 ⋅ 阅读:(17) ⋅ 点赞:(0)

桥接模式:就是进行拼接组装
在这里插入图片描述
应用举例:
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;
}