当前位置: 首页 > news >正文

第七章:桥接模式 - 抽象与实现的桥梁大师

第七章:桥接模式 - 抽象与实现的桥梁大师

故事延续:桥梁构建的智慧之道

在Adapter展示完他的转接艺术后,Bridge仙风道骨地走出,他手持一柄晶莹长桥作为法器,将桥往空中一抛,桥身便连接了抽象与实现两座虚无的山峰。这位老者的声音平和而深邃,回荡在圣殿之中。

“Adapter兄是事后补救,老夫则是防患于未然。” Bridge抚须笑道,“我的武学核心在于——将抽象部分与它的实现部分分离,使它们都可以独立地变化。这样,功能的扩展就不必担心平台变更,平台的升级也无须改动功能逻辑。”

桥接模式的武学精要

核心心法

Bridge双手结印,空中的桥梁发出柔和的光芒:“我的十六字真言是——抽象实现分离,各自独立演化。通过建立一座桥梁,我可以让抽象层和实现层各自沿着自己的轴线独立发展,避免因一方的变化而影响另一方。”

C++ 代码实战
#include <iostream>
#include <memory>
#include <string>
#include <vector>
#include <unordered_map>// 实现接口:绘图API
class DrawingAPI {
public:virtual ~DrawingAPI() = default;virtual void drawCircle(double x, double y, double radius) = 0;virtual void drawRectangle(double x, double y, double width, double height) = 0;virtual void drawText(double x, double y, const std::string& text) = 0;virtual void setColor(const std::string& color) = 0;virtual std::string getAPIInfo() const = 0;
};// 具体实现:OpenGL绘图API
class OpenGLDrawing : public DrawingAPI {
private:std::string currentColor_;public:void drawCircle(double x, double y, double radius) override {std::cout << "🔵 OpenGL绘制圆形: 位置(" << x << ", " << y << "), 半径" << radius << ", 颜色: " << currentColor_ << std::endl;}void drawRectangle(double x, double y, double width, double height) override {std::cout << "🟦 OpenGL绘制矩形: 位置(" << x << ", " << y << "), 尺寸" << width << "x" << height << ", 颜色: " << currentColor_ << std::endl;}void drawText(double x, double y, const std::string& text) override {std::cout << "📝 OpenGL绘制文本: 位置(" << x << ", " << y << "), 内容: '" << text << "', 颜色: " << currentColor_ << std::endl;}void setColor(const std::string& color) override {currentColor_ = color;std::cout << "🎨 OpenGL设置颜色: " << color << std::endl;}std::string getAPIInfo() const override {return "OpenGL图形API (硬件加速)";}// OpenGL特有功能void enable3DMode() {std::cout = "🚀 OpenGL开启3D模式" << std::endl;}
};// 具体实现:SVG绘图API
class SVGDrawing : public DrawingAPI {
private:std::string currentColor_;std::vector<std::string> svgElements_;public:void drawCircle(double x, double y, double radius) override {std::string element = "<circle cx='" + std::to_string(x) + "' cy='" + std::to_string(y) + "' r='" + std::to_string(radius) + "' fill='" + currentColor_ + "'/>";svgElements_.push_back(element);std::cout << "🔵 SVG绘制圆形: " << element << std::endl;}void drawRectangle(double x, double y, double width, double height) override {std::string element = "<rect x='" + std::to_string(x) + "' y='" + std::to_string(y) + "' width='" + std::to_string(width) + "' height='" + std::to_string(height) + "' fill='" + currentColor_ + "'/>";svgElements_.push_back(element);std::cout << "🟦 SVG绘制矩形: " << element << std::endl;}void drawText(double x, double y, const std::string& text) override {std::string element = "<text x='" + std::to_string(x) + "' y='" + std::to_string(y) + "' fill='" + currentColor_ + "'>" + text + "</text>";svgElements_.push_back(element);std::cout << "📝 SVG绘制文本: " << element << std::endl;}void setColor(const std::string& color) override {currentColor_ = color;std::cout << "🎨 SVG设置颜色: " << color << std::endl;}std::string getAPIInfo() const override {return "SVG矢量图形 (分辨率无关)";}// SVG特有功能std::string generateSVGDocument() const {std::string svg = "<svg xmlns='http://www.w3.org/2000/svg' width='800' height='600'>\n";for (const auto& element : svgElements_) {svg += "  " + element + "\n";}svg += "</svg>";return svg;}
};// 具体实现:Canvas 2D绘图API
class CanvasDrawing : public DrawingAPI {
private:std::string currentColor_;public:void drawCircle(double x, double y, double radius) override {std::cout << "🔵 Canvas绘制圆形: context.arc(" << x << ", " << y << ", " << radius << ", 0, 2 * Math.PI), 颜色: " << currentColor_ << std::endl;}void drawRectangle(double x, double y, double width, double height) override {std::cout << "🟦 Canvas绘制矩形: context.rect(" << x << ", " << y << ", " << width << ", " << height << "), 颜色: " << currentColor_ << std::endl;}void drawText(double x, double y, const std::string& text) override {std::cout << "📝 Canvas绘制文本: context.fillText('" << text << "', " << x << ", " << y << "), 颜色: " << currentColor_ << std::endl;}void setColor(const std::string& color) override {currentColor_ = color;std::cout << "🎨 Canvas设置颜色: " << color << std::endl;}std::string getAPIInfo() const override {return "HTML5 Canvas (网页绘图)";}// Canvas特有功能void beginPath() {std::cout << "🖊️ Canvas开始路径" << std::endl;}void closePath() {std::cout << "🔚 Canvas关闭路径" << std::endl;}
};// 抽象类:形状
class Shape {
protected:std::shared_ptr<DrawingAPI> drawingAPI_;std::string color_;public:Shape(std::shared_ptr<DrawingAPI> drawingAPI, const std::string& color = "black"): drawingAPI_(drawingAPI), color_(color) {drawingAPI_->setColor(color_);}virtual ~Shape() = default;virtual void draw() = 0;virtual void resize(double factor) = 0;virtual double calculateArea() const = 0;virtual std::string getShapeInfo() const = 0;// 改变绘图API(桥接的关键)void setDrawingAPI(std::shared_ptr<DrawingAPI> drawingAPI) {drawingAPI_ = drawingAPI;drawingAPI_->setColor(color_);std::cout << "🌉 切换绘图API: " << drawingAPI_->getAPIInfo() << std::endl;}// 改变颜色void setColor(const std::string& color) {color_ = color;drawingAPI_->setColor(color_);}std::string getDrawingAPIInfo() const {return drawingAPI_->getAPIInfo();}
};// 精确抽象:圆形
class Circle : public Shape {
private:double x_, y_, radius_;public:Circle(std::shared_ptr<DrawingAPI> drawingAPI, double x, double y, double radius, const std::string& color = "black"): Shape(drawingAPI, color), x_(x), y_(y), radius_(radius) {}void draw() override {std::cout << "🎯 绘制圆形..." << std::endl;drawingAPI_->drawCircle(x_, y_, radius_);}void resize(double factor) override {radius_ *= factor;std::cout << "📐 调整圆形大小: 新半径 = " << radius_ << std::endl;}double calculateArea() const override {return 3.14159 * radius_ * radius_;}std::string getShapeInfo() const override {return "圆形 [位置: (" + std::to_string(x_) + ", " + std::to_string(y_) + "), 半径: " + std::to_string(radius_) + ", 颜色: " + color_ + "]";}// 圆形特有方法void setPosition(double x, double y) {x_ = x;y_ = y;std::cout << "📍 移动圆形到位置: (" << x_ << ", " << y_ << ")" << std::endl;}
};// 精确抽象:矩形
class Rectangle : public Shape {
private:double x_, y_, width_, height_;public:Rectangle(std::shared_ptr<DrawingAPI> drawingAPI, double x, double y, double width, double height, const std::string& color = "black"): Shape(drawingAPI, color), x_(x), y_(y), width_(width), height_(height) {}void draw() override {std::cout << "🎯 绘制矩形..." << std::endl;drawingAPI_->drawRectangle(x_, y_, width_, height_);}void resize(double factor) override {width_ *= factor;height_ *= factor;std::cout << "📐 调整矩形大小: 新尺寸 = " << width_ << "x" << height_ << std::endl;}double calculateArea() const override {return width_ * height_;}std::string getShapeInfo() const override {return "矩形 [位置: (" + std::to_string(x_) + ", " + std::to_string(y_) + "), 尺寸: " + std::to_string(width_) + "x" + std::to_string(height_) + ", 颜色: " + color_ + "]";}// 矩形特有方法void rotate(double angle) {std::cout << "🔄 旋转矩形: " << angle << "度" << std::endl;}
};// 精确抽象:文本标签
class TextLabel : public Shape {
private:double x_, y_;std::string text_;public:TextLabel(std::shared_ptr<DrawingAPI> drawingAPI, double x, double y, const std::string& text, const std::string& color = "black"): Shape(drawingAPI, color), x_(x), y_(y), text_(text) {}void draw() override {std::cout << "🎯 绘制文本..." << std::endl;drawingAPI_->drawText(x_, y_, text_);}void resize(double factor) override {std::cout << "📐 文本大小调整因子: " << factor << " (在真实系统中会影响字体大小)" << std::endl;}double calculateArea() const override {return text_.length() * 10; // 简化的面积计算}std::string getShapeInfo() const override {return "文本标签 [位置: (" + std::to_string(x_) + ", " + std::to_string(y_) + "), 内容: '" + text_ + "', 颜色: " + color_ + "]";}// 文本特有方法void setText(const std::string& text) {text_ = text;std::cout << "📝 更新文本内容: " << text_ << std::endl;}
};

UML 武功秘籍图

uses
«interface»
DrawingAPI
+drawCircle(double, double, double) : void
+drawRectangle(double, double, double, double) : void
+drawText(double, double, string) : void
+setColor(string) : void
+getAPIInfo() : string
OpenGLDrawing
-string currentColor_
+drawCircle(double, double, double) : void
+drawRectangle(double, double, double, double) : void
+drawText(double, double, string) : void
+setColor(string) : void
+getAPIInfo() : string
+enable3DMode() : void
SVGDrawing
-string currentColor_
-vector<string> svgElements_
+drawCircle(double, double, double) : void
+drawRectangle(double, double, double, double) : void
+drawText(double, double, string) : void
+setColor(string) : void
+getAPIInfo() : string
+generateSVGDocument() : string
CanvasDrawing
-string currentColor_
+drawCircle(double, double, double) : void
+drawRectangle(double, double, double, double) : void
+drawText(double, double, string) : void
+setColor(string) : void
+getAPIInfo() : string
+beginPath() : void
+closePath() : void
«abstract»
Shape
#shared_ptr<DrawingAPI> drawingAPI_
#string color_
+draw() : void
+resize(double) : void
+calculateArea() : double
+getShapeInfo() : string
+setDrawingAPI(shared_ptr<DrawingAPI>) : void
+setColor(string) : void
+getDrawingAPIInfo() : string
Circle
-double x_
-double y_
-double radius_
+draw() : void
+resize(double) : void
+calculateArea() : double
+getShapeInfo() : string
+setPosition(double, double) : void
Rectangle
-double x_
-double y_
-double width_
-double height_
+draw() : void
+resize(double) : void
+calculateArea() : double
+getShapeInfo() : string
+rotate(double) : void
TextLabel
-double x_
-double y_
-string text_
+draw() : void
+resize(double) : void
+calculateArea() : double
+getShapeInfo() : string
+setText(string) : void

实战演练:跨平台UI框架

#include <map>
#include <algorithm>// 更复杂的桥接模式应用:跨平台UI框架// 实现接口:窗口系统
class WindowImpl {
public:virtual ~WindowImpl() = default;virtual void createWindow(int width, int height, const std::string& title) = 0;virtual void closeWindow() = 0;virtual void maximizeWindow() = 0;virtual void minimizeWindow() = 0;virtual void setWindowPosition(int x, int y) = 0;virtual std::string getPlatformInfo() const = 0;
};// 具体实现:Windows窗口系统
class WindowsWindowImpl : public WindowImpl {
private:std::string title_;int width_, height_;bool isCreated_;public:WindowsWindowImpl() : isCreated_(false), width_(0), height_(0) {}void createWindow(int width, int height, const std::string& title) override {width_ = width;height_ = height;title_ = title;isCreated_ = true;std::cout << "🪟 创建Windows窗口: " << title_ << " [" << width_ << "x" << height_ << "]" << std::endl;std::cout << "   - 使用Win32 API" << std::endl;std::cout << "   - 支持Aero效果" << std::endl;std::cout << "   - 集成任务栏" << std::endl;}void closeWindow() override {if (isCreated_) {std::cout << "❌ 关闭Windows窗口: " << title_ << std::endl;isCreated_ = false;}}void maximizeWindow() override {std::cout << "⬆️ 最大化Windows窗口" << std::endl;}void minimizeWindow() override {std::cout << "⬇️ 最小化Windows窗口到任务栏" << std::endl;}void setWindowPosition(int x, int y) override {std::cout << "📍 设置Windows窗口位置: (" << x << ", " << y << ")" << std::endl;}std::string getPlatformInfo() const override {return "Windows窗口系统 (Win32 API)";}// Windows特有功能void enableTransparency() {std::cout = "🔮 Windows启用窗口透明效果" << std::endl;}
};// 具体实现:macOS窗口系统
class MacWindowImpl : public WindowImpl {
private:std::string title_;int width_, height_;bool isCreated_;public:MacWindowImpl() : isCreated_(false), width_(0), height_(0) {}void createWindow(int width, int height, const std::string& title) override {width_ = width;height_ = height;title_ = title;isCreated_ = true;std::cout << "🍎 创建macOS窗口: " << title_ << " [" << width_ << "x" << height_ << "]" << std::endl;std::cout << "   - 使用Cocoa框架" << std::endl;std::cout << "   - 支持毛玻璃效果" << std::endl;std::cout << "   - 集成菜单栏" << std::endl;}void closeWindow() override {if (isCreated_) {std::cout << "❌ 关闭macOS窗口: " << title_ << std::endl;isCreated_ = false;}}void maximizeWindow() override {std::cout << "⬆️ 最大化macOS窗口到全屏" << std::endl;}void minimizeWindow() override {std::cout << "⬇️ 最小化macOS窗口到Dock" << std::endl;}void setWindowPosition(int x, int y) override {std::cout << "📍 设置macOS窗口位置: (" << x << ", " << y << ")" << std::endl;}std::string getPlatformInfo() const override {return "macOS窗口系统 (Cocoa框架)";}// macOS特有功能void enableVibrancy() {std::cout = "✨ macOS启用活力效果" << std::endl;}
};// 具体实现:Linux窗口系统
class LinuxWindowImpl : public WindowImpl {
private:std::string title_;int width_, height_;bool isCreated_;public:LinuxWindowImpl() : isCreated_(false), width_(0), height_(0) {}void createWindow(int width, int height, const std::string& title) override {width_ = width;height_ = height;title_ = title;isCreated_ = true;std::cout << "🐧 创建Linux窗口: " << title_ << " [" << width_ << "x" << height_ << "]" << std::endl;std::cout << "   - 使用GTK+框架" << std::endl;std::cout << "   - 支持主题定制" << std::endl;std::cout << "   - 轻量级设计" << std::endl;}void closeWindow() override {if (isCreated_) {std::cout << "❌ 关闭Linux窗口: " << title_ << std::endl;isCreated_ = false;}}void maximizeWindow() override {std::cout << "⬆️ 最大化Linux窗口" << std::endl;}void minimizeWindow() override {std::cout << "⬇️ 最小化Linux窗口" << std::endl;}void setWindowPosition(int x, int y) override {std::cout << "📍 设置Linux窗口位置: (" << x << ", " << y << ")" << std::endl;}std::string getPlatformInfo() const override {return "Linux窗口系统 (GTK+框架)";}// Linux特有功能void enableCustomTheme() {std::cout = "🎨 Linux启用自定义主题" << std::endl;}
};// 抽象类:窗口
class Window {
protected:std::shared_ptr<WindowImpl> impl_;std::string title_;int width_, height_;public:Window(std::shared_ptr<WindowImpl> impl, const std::string& title, int width, int height): impl_(impl), title_(title), width_(width), height_(height) {}virtual ~Window() = default;virtual void show() = 0;virtual void hide() = 0;virtual void setTitle(const std::string& title) = 0;virtual std::string getWindowInfo() const = 0;// 桥接的关键:可以动态改变实现void setWindowImpl(std::shared_ptr<WindowImpl> impl) {impl_ = impl;std::cout << "🌉 切换窗口实现: " << impl_->getPlatformInfo() << std::endl;}// 基础窗口操作void create() {impl_->createWindow(width_, height_, title_);}void close() {impl_->closeWindow();}void maximize() {impl_->maximizeWindow();}void minimize() {impl_->minimizeWindow();}void setPosition(int x, int y) {impl_->setWindowPosition(x, y);}
};// 精确抽象:对话框窗口
class DialogWindow : public Window {
private:std::string message_;std::vector<std::string> buttons_;public:DialogWindow(std::shared_ptr<WindowImpl> impl, const std::string& title, int width, int height, const std::string& message): Window(impl, title, width, height), message_(message) {}void show() override {std::cout << "💬 显示对话框: " << title_ << std::endl;std::cout << "   消息: " << message_ << std::endl;create();if (!buttons_.empty()) {std::cout << "   按钮: ";for (const auto& button : buttons_) {std::cout << "[" << button << "] ";}std::cout << std::endl;}}void hide() override {std::cout << "🚫 隐藏对话框: " << title_ << std::endl;close();}void setTitle(const std::string& title) override {title_ = title;std::cout << "🏷️ 设置对话框标题: " << title_ << std::endl;}std::string getWindowInfo() const override {return "对话框窗口 [标题: " + title_ + ", 尺寸: " + std::to_string(width_) + "x" + std::to_string(height_) + ", 平台: " + impl_->getPlatformInfo() + "]";}// 对话框特有方法void addButton(const std::string& buttonText) {buttons_.push_back(buttonText);std::cout << "➕ 添加对话框按钮: " << buttonText << std::endl;}void setMessage(const std::string& message) {message_ = message;std::cout << "📝 设置对话框消息: " << message_ << std::endl;}
};// 精确抽象:主窗口
class MainWindow : public Window {
private:std::vector<std::string> menuItems_;std::string status_;public:MainWindow(std::shared_ptr<WindowImpl> impl, const std::string& title, int width, int height): Window(impl, title, width, height), status_("就绪") {}void show() override {std::cout << "🖥️ 显示主窗口: " << title_ << std::endl;create();if (!menuItems_.empty()) {std::cout << "   菜单项: ";for (const auto& item : menuItems_) {std::cout << item << " | ";}std::cout << std::endl;}std::cout << "   状态: " << status_ << std::endl;}void hide() override {std::cout << "🚫 隐藏主窗口: " << title_ << std::endl;close();}void setTitle(const std::string& title) override {title_ = title;std::cout << "🏷️ 设置主窗口标题: " << title_ << std::endl;}std::string getWindowInfo() const override {return "主窗口 [标题: " + title_ + ", 尺寸: " + std::to_string(width_) + "x" + std::to_string(height_) + ", 平台: " + impl_->getPlatformInfo() + "]";}// 主窗口特有方法void addMenuItem(const std::string& item) {menuItems_.push_back(item);std::cout << "➕ 添加菜单项: " << item << std::endl;}void setStatus(const std::string& status) {status_ = status;std::cout << "📊 设置状态: " << status_ << std::endl;}void showFullScreen() {std::cout << "🖥️ 进入全屏模式" << std::endl;maximize();}
};// 精确抽象:工具窗口
class ToolWindow : public Window {
private:std::string toolType_;bool isDocked_;public:ToolWindow(std::shared_ptr<WindowImpl> impl, const std::string& title, int width, int height, const std::string& toolType): Window(impl, title, width, height), toolType_(toolType), isDocked_(false) {}void show() override {std::cout << "🛠️ 显示工具窗口: " << title_ << " (" << toolType_ << ")" << std::endl;create();std::cout << "   停靠状态: " << (isDocked_ ? "已停靠" : "浮动") << std::endl;}void hide() override {std::cout << "🚫 隐藏工具窗口: " << title_ << std::endl;close();}void setTitle(const std::string& title) override {title_ = title;std::cout << "🏷️ 设置工具窗口标题: " << title_ << std::endl;}std::string getWindowInfo() const override {return "工具窗口 [标题: " + title_ + ", 工具类型: " + toolType_ + ", 尺寸: " + std::to_string(width_) + "x" + std::to_string(height_) + ", 平台: " + impl_->getPlatformInfo() + "]";}// 工具窗口特有方法void dockWindow() {isDocked_ = true;std::cout = "📌 停靠工具窗口" << std::endl;}void undockWindow() {isDocked_ = false;std::cout = "🔄 取消停靠工具窗口" << std::endl;}void setToolType(const std::string& toolType) {toolType_ = toolType;std::cout << "🔧 设置工具类型: " << toolType_ << std::endl;}
};

桥接模式的招式解析

招式一:运行时桥接切换
// 桥接管理器:动态管理抽象和实现的组合
class BridgeManager {
private:std::unordered_map<std::string, std::shared_ptr<DrawingAPI>> drawingAPIs_;std::unordered_map<std::string, std::shared_ptr<WindowImpl>> windowImpls_;public:BridgeManager() {initializeAPIs();initializeWindowImpls();}void initializeAPIs() {drawingAPIs_["opengl"] = std::make_shared<OpenGLDrawing>();drawingAPIs_["svg"] = std::make_shared<SVGDrawing>();drawingAPIs_["canvas"] = std::make_shared<CanvasDrawing>();std::cout << "📚 初始化绘图API桥接..." << std::endl;}void initializeWindowImpls() {windowImpls_["windows"] = std::make_shared<WindowsWindowImpl>();windowImpls_["macos"] = std::make_shared<MacWindowImpl>();windowImpls_["linux"] = std::make_shared<LinuxWindowImpl>();std::cout << "📚 初始化窗口实现桥接..." << std::endl;}// 获取绘图APIstd::shared_ptr<DrawingAPI> getDrawingAPI(const std::string& name) {auto it = drawingAPIs_.find(name);if (it != drawingAPIs_.end()) {return it->second;}return nullptr;}// 获取窗口实现std::shared_ptr<WindowImpl> getWindowImpl(const std::string& name) {auto it = windowImpls_.find(name);if (it != windowImpls_.end()) {return it->second;}return nullptr;}// 获取所有可用的APIstd::vector<std::string> getAvailableDrawingAPIs() const {std::vector<std::string> apis;for (const auto& pair : drawingAPIs_) {apis.push_back(pair.first);}return apis;}std::vector<std::string> getAvailableWindowImpls() const {std::vector<std::string> impls;for (const auto& pair : windowImpls_) {impls.push_back(pair.first);}return impls;}// 动态创建形状与API的组合std::shared_ptr<Circle> createCircle(const std::string& apiName, double x, double y, double radius) {auto api = getDrawingAPI(apiName);if (api) {return std::make_shared<Circle>(api, x, y, radius);}return nullptr;}std::shared_ptr<MainWindow> createMainWindow(const std::string& implName, const std::string& title) {auto impl = getWindowImpl(implName);if (impl) {return std::make_shared<MainWindow>(impl, title, 800, 600);}return nullptr;}
};
招式二:桥接模式与策略模式结合
// 结合策略模式的增强桥接
class AdvancedBridgeSystem {
private:BridgeManager bridgeManager_;public:// 演示运行时动态切换void demonstrateDynamicSwitching() {std::cout << "\n🔄 动态桥接切换演示" << std::endl;std::cout << "=====================" << std::endl;// 创建一个圆形,初始使用OpenGLauto circle = bridgeManager_.createCircle("opengl", 100, 100, 50);if (circle) {std::cout << "\n初始配置:" << std::endl;std::cout << "形状: " << circle->getShapeInfo() << std::endl;std::cout << "API: " << circle->getDrawingAPIInfo() << std::endl;circle->draw();// 动态切换到SVGstd::cout << "\n🌉 动态切换到SVG..." << std::endl;circle->setDrawingAPI(bridgeManager_.getDrawingAPI("svg"));circle->draw();// 动态切换到Canvasstd::cout << "\n🌉 动态切换到Canvas..." << std::endl;circle->setDrawingAPI(bridgeManager_.getDrawingAPI("canvas"));circle->draw();// 改变颜色std::cout << "\n🎨 改变颜色..." << std::endl;circle->setColor("blue");circle->draw();}}// 演示跨平台窗口创建void demonstrateCrossPlatformWindows() {std::cout << "\n🖥️ 跨平台窗口演示" << std::endl;std::cout << "==================" << std::endl;auto platforms = bridgeManager_.getAvailableWindowImpls();for (const auto& platform : platforms) {std::cout << "\n创建 " << platform << " 平台窗口:" << std::endl;auto window = bridgeManager_.createMainWindow(platform, platform + "应用程序");if (window) {window->show();window->addMenuItem("文件");window->addMenuItem("编辑");window->setStatus("运行中...");std::cout << "窗口信息: " << window->getWindowInfo() << std::endl;window->hide();}}}// 性能测试:不同实现的性能比较void performanceComparison() {std::cout << "\n⚡ 性能比较测试" << std::endl;std::cout << "================" << std::endl;auto apis = bridgeManager_.getAvailableDrawingAPIs();for (const auto& apiName : apis) {std::cout << "\n测试 " << apiName << " 性能:" << std::endl;auto circle = bridgeManager_.createCircle(apiName, 200, 200, 30);if (circle) {auto start = std::chrono::high_resolution_clock::now();// 模拟多次绘制for (int i = 0; i < 1000; ++i) {circle->draw();}auto end = std::chrono::high_resolution_clock::now();auto duration = std::chrono::duration_cast<std::chrono::microseconds>(end - start);std::cout << "✅ " << apiName << " 完成1000次绘制用时: " << duration.count() << " 微秒" << std::endl;}}}
};

完整测试代码

// 测试桥接模式
void testBridgePattern() {std::cout << "=== 桥接模式测试开始 ===" << std::endl;// 测试图形绘制桥接std::cout << "\n--- 图形绘制桥接测试 ---" << std::endl;// 创建不同的绘图APIauto openGL = std::make_shared<OpenGLDrawing>();auto svg = std::make_shared<SVGDrawing>();auto canvas = std::make_shared<CanvasDrawing>();// 使用OpenGL绘制圆形Circle openGLCircle(openGL, 50, 50, 25, "red");std::cout << "形状: " << openGLCircle.getShapeInfo() << std::endl;std::cout << "API: " << openGLCircle.getDrawingAPIInfo() << std::endl;openGLCircle.draw();// 切换到SVG绘制同一个圆形std::cout << "\n🌉 切换到SVG实现..." << std::endl;openGLCircle.setDrawingAPI(svg);openGLCircle.setColor("green");openGLCircle.draw();// 创建矩形并使用CanvasRectangle canvasRect(canvas, 100, 100, 80, 60, "blue");canvasRect.draw();std::cout << "矩形面积: " << canvasRect.calculateArea() << std::endl;// 测试文本标签TextLabel openGLText(openGL, 150, 50, "Hello Bridge Pattern!", "purple");openGLText.draw();// 测试窗口系统桥接std::cout << "\n--- 窗口系统桥接测试 ---" << std::endl;// 创建不同平台的窗口实现auto windowsImpl = std::make_shared<WindowsWindowImpl>();auto macImpl = std::make_shared<MacWindowImpl>();auto linuxImpl = std::make_shared<LinuxWindowImpl>();// 创建对话框并在不同平台显示DialogWindow windowsDialog(windowsImpl, "Windows对话框", 400, 300, "这是一个Windows风格对话框");windowsDialog.addButton("确定");windowsDialog.addButton("取消");windowsDialog.show();std::cout << "窗口信息: " << windowsDialog.getWindowInfo() << std::endl;// 切换到macOS实现std::cout << "\n🌉 切换到macOS实现..." << std::endl;windowsDialog.setWindowImpl(macImpl);windowsDialog.setTitle("macOS对话框");windowsDialog.show();// 创建主窗口MainWindow linuxMain(linuxImpl, "Linux主窗口", 1024, 768);linuxMain.addMenuItem("文件");linuxMain.addMenuItem("编辑");linuxMain.addMenuItem("视图");linuxMain.setStatus("就绪");linuxMain.show();// 测试桥接管理器std::cout << "\n--- 桥接管理器测试 ---" << std::endl;BridgeManager bridgeManager;auto availableAPIs = bridgeManager.getAvailableDrawingAPIs();std::cout << "可用的绘图API: ";for (const auto& api : availableAPIs) {std::cout << api << " ";}std::cout << std::endl;auto availableImpls = bridgeManager.getAvailableWindowImpls();std::cout << "可用的窗口实现: ";for (const auto& impl : availableImpls) {std::cout << impl << " ";}std::cout << std::endl;// 使用桥接管理器创建形状auto managedCircle = bridgeManager.createCircle("svg", 300, 200, 40);if (managedCircle) {managedCircle->setColor("orange");managedCircle->draw();}// 测试高级桥接系统std::cout << "\n--- 高级桥接系统测试 ---" << std::endl;AdvancedBridgeSystem advancedSystem;advancedSystem.demonstrateDynamicSwitching();advancedSystem.demonstrateCrossPlatformWindows();advancedSystem.performanceComparison();std::cout << "\n=== 桥接模式测试结束 ===" << std::endl;
}// 实战应用:跨平台图形编辑器
class CrossPlatformGraphicsEditor {
private:BridgeManager bridgeManager_;std::vector<std::shared_ptr<Shape>> shapes_;std::shared_ptr<WindowImpl> currentPlatform_;public:CrossPlatformGraphicsEditor(const std::string& platform) {currentPlatform_ = bridgeManager_.getWindowImpl(platform);std::cout << "\n🎨 创建跨平台图形编辑器 (" << platform << "版本)" << std::endl;}void run() {std::cout << "\n🚀 启动图形编辑器..." << std::endl;// 创建主窗口auto mainWindow = std::make_shared<MainWindow>(currentPlatform_, "图形编辑器", 1200, 800);mainWindow->show();// 创建工具栏auto toolWindow = std::make_shared<ToolWindow>(currentPlatform_, "绘图工具", 200, 400, "绘图");toolWindow->show();// 演示图形绘制demonstrateDrawing();// 演示平台切换demonstratePlatformSwitching();mainWindow->hide();toolWindow->hide();}private:void demonstrateDrawing() {std::cout << "\n🎯 图形绘制演示" << std::endl;std::cout << "================" << std::endl;// 使用不同API创建图形auto apis = bridgeManager_.getAvailableDrawingAPIs();for (size_t i = 0; i < apis.size(); ++i) {std::cout << "\n使用 " << apis[i] << " 创建图形:" << std::endl;auto circle = bridgeManager_.createCircle(apis[i], 100 + i * 150, 100, 30 + i * 10);if (circle) {circle->setColor(getColorByIndex(i));circle->draw();shapes_.push_back(circle);}auto rect = std::make_shared<Rectangle>(bridgeManager_.getDrawingAPI(apis[i]), 100 + i * 150, 200, 60 + i * 10, 40 + i * 5,getColorByIndex(i + 1));rect->draw();shapes_.push_back(rect);}std::cout << "\n📊 总共创建了 " << shapes_.size() << " 个图形" << std::endl;}void demonstratePlatformSwitching() {std::cout << "\n🌉 平台切换演示" << std::endl;std::cout << "================" << std::endl;auto platforms = bridgeManager_.getAvailableWindowImpls();for (const auto& platform : platforms) {std::cout << "\n切换到 " << platform << " 平台:" << std::endl;auto dialog = std::make_shared<DialogWindow>(bridgeManager_.getWindowImpl(platform),platform + " 提示",300, 200,"这是 " + platform + " 平台的对话框");dialog->addButton("确定");dialog->show();dialog->hide();}}std::string getColorByIndex(int index) {std::vector<std::string> colors = {"red", "green", "blue", "orange", "purple", "cyan"};return colors[index % colors.size()];}
};int main() {testBridgePattern();// 运行跨平台图形编辑器示例std::cout << "\n🎮 跨平台图形编辑器示例:" << std::endl;// 创建不同平台的编辑器实例CrossPlatformGraphicsEditor windowsEditor("windows");windowsEditor.run();CrossPlatformGraphicsEditor macEditor("macos");macEditor.run();CrossPlatformGraphicsEditor linuxEditor("linux");linuxEditor.run();return 0;
}

桥接模式的武学心得

适用场景
  • 多维度变化:当一个类需要在多个维度上独立扩展时
  • 平台无关开发:需要开发跨平台的应用程序时
  • 接口与实现分离:希望接口和实现可以独立变化时
  • 避免永久绑定:不希望抽象和实现之间有一个固定的绑定关系
优点
  • 分离接口与实现:抽象和实现可以独立扩展,不会相互影响
  • 提高可扩展性:可以独立地对抽象和实现进行扩展
  • 实现细节对客户透明:客户代码只需要知道抽象接口
  • 符合开闭原则:易于扩展新的抽象和实现
缺点
  • 增加复杂度:增加了系统的理解和设计难度
  • 需要正确识别维度:需要正确识别出系统中变化的维度
  • 要求高设计能力:对设计者的抽象能力要求较高

武林高手的点评

Adapter 赞叹道:“Bridge 兄的桥梁构建确实高明!能够在设计阶段就预防接口与实现的紧耦合问题,这比我的事后补救更加优雅。”

Abstract Factory 也点头称赞:“Bridge 兄专注于抽象与实现的分离,而我更关注产品家族的创建。我们都在不同的维度上解决软件设计的复杂性问题。”

Bridge 谦虚回应:“诸位过奖了。每个模式都有其适用场景。在需要处理多维度变化时,我的桥接模式确实能发挥重要作用。但在创建相关对象家族时,Abstract Factory 兄的方法更加合适。”

下章预告

在Bridge展示完他的桥梁构建之道后,Composite 身形奇特地走出,他时而是一个完整的巨人,时而又散开成一群小兵,但无论合体还是分散,行动都整齐划一。

“Bridge 兄的抽象实现分离确实精妙,但在处理层次结构时,需要更加统一的处理方式。” Composite 瓮声瓮气地说道,“下一章,我将展示如何通过组合模式让单个对象与组合对象具有一致的接口!”

架构老人眼中露出赞许:“善!层次结构的统一处理确实是复杂系统设计的关键。下一章,就请 Composite 展示他的组合艺术!”


欲知 Composite 如何通过组合模式统一处理层次结构,且听下回分解!

http://www.dtcms.com/a/446098.html

相关文章:

  • 短视频推荐的底层逻辑:大数据如何 “读懂” 你的每一次滑动
  • 嘉兴市建设工程监理协会网站学做美食看哪个网站
  • 《SpringBoot入门实战:从HelloWorld到RESTful接口(支持GET/POST/PUT/DELETE,附Git版本控制)》
  • 信用网站一体化建设网页制作大宝库
  • gRPC从0到1系列【19】
  • 嵌入式Linux Qt触摸屏问题诊断与解决报告
  • gRPC从0到1系列【20】
  • CTFHub 信息泄露通关笔记10:SVN泄露(2种方法)
  • 手机网站开发环境搭建网站建设个人网银
  • 使用 jintellitype 库在 Java 程序中实现监听 Windows 全局快捷键(热键)
  • Python驱动Ksycopg2连接和使用Kingbase:国产数据库实战指南
  • 广州网站网站建设福建建站公司
  • ⚡ arm 32位嵌入式 Linux 系统移植 QT 程序
  • VR大空间资料 02 —— 常用Body IK对比
  • 什么是网站建设需求重庆建设工程信息网查询系统
  • 高校思政专题网站建设南京有哪些知名的网站建设
  • 【SpringCloud(2)】微服务注册中心:Eureka、Zookeeper;CAP分析;服务注册与服务发现;单机/集群部署Eureka;连接注册中心
  • ionic 浮动框详解与应用
  • 开源 C++ QT QML 开发(五)复杂控件--Gridview
  • 下载建设银行官方网站工程承包合同协议书
  • 第九章:装饰器模式 - 动态增强的艺术大师
  • OpenAI 发布 GPT-5 Instant:AI 有了 “情感温度计“
  • 苏州做网站公司选苏州聚尚网络做百度百科的网站
  • SSE与轮询技术实时对比演示
  • 示范专业网站建设深圳联雅网站建设
  • php 8.4.13 更新日志
  • MongoDB 认证失败(错误码 18)
  • 深圳网站建设主页什么公司需要建立网站吗
  • 陕西省建设信息管理网站网站开发 家具销售 文献
  • 数学标准库