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

C++ 设计模式综合实例

C++ 设计模式综合实例

下面是一个综合使用工厂模式、适配器、装饰器、代理和外观模式的完整C++示例。这个例子模拟一个图形处理系统。

1. 基础接口和类

#include <iostream>
#include <memory>
#include <vector>
#include <string>// 图形接口
class Shape {
public:virtual ~Shape() = default;virtual void draw() const = 0;virtual std::string getName() const = 0;
};// 具体图形类
class Circle : public Shape {
public:void draw() const override {std::cout << "Drawing Circle" << std::endl;}std::string getName() const override {return "Circle";}
};class Rectangle : public Shape {
public:void draw() const override {std::cout << "Drawing Rectangle" << std::endl;}std::string getName() const override {return "Rectangle";}
};class Triangle : public Shape {
public:void draw() const override {std::cout << "Drawing Triangle" << std::endl;}std::string getName() const override {return "Triangle";}
};

2. 工厂模式 - 创建对象

// 图形工厂
class ShapeFactory {
public:enum ShapeType { CIRCLE, RECTANGLE, TRIANGLE };static std::unique_ptr<Shape> createShape(ShapeType type) {switch(type) {case CIRCLE:    return std::make_unique<Circle>();case RECTANGLE: return std::make_unique<Rectangle>();case TRIANGLE:  return std::make_unique<Triangle>();default:        return nullptr;}}
};

3. 适配器模式 - 接口转换

// 第三方图形类(不兼容接口)
class LegacyGraphics {
public:void render(const std::string& shapeName) {std::cout << "Legacy rendering: " << shapeName << std::endl;}
};// 适配器
class LegacyGraphicsAdapter : public Shape {
private:LegacyGraphics legacyGraphics;std::string name;public:LegacyGraphicsAdapter(const std::string& name) : name(name) {}void draw() const override {legacyGraphics.render(name);}std::string getName() const override {return name;}
};

4. 装饰器模式 - 动态添加功能

// 基础装饰器
class ShapeDecorator : public Shape {
protected:std::unique_ptr<Shape> decoratedShape;public:ShapeDecorator(std::unique_ptr<Shape> shape) : decoratedShape(std::move(shape)) {}void draw() const override {decoratedShape->draw();}std::string getName() const override {return decoratedShape->getName();}
};// 具体装饰器 - 添加颜色
class ColoredShape : public ShapeDecorator {
private:std::string color;public:ColoredShape(std::unique_ptr<Shape> shape, const std::string& color): ShapeDecorator(std::move(shape)), color(color) {}void draw() const override {std::cout << "Applying color: " << color << std::endl;ShapeDecorator::draw();}std::string getName() const override {return color + " " + ShapeDecorator::getName();}
};// 具体装饰器 - 添加边框
class BorderedShape : public ShapeDecorator {
private:int borderWidth;public:BorderedShape(std::unique_ptr<Shape> shape, int width): ShapeDecorator(std::move(shape)), borderWidth(width) {}void draw() const override {ShapeDecorator::draw();std::cout << "Adding border with width: " << borderWidth << std::endl;}std::string getName() const override {return ShapeDecorator::getName() + " with border";}
};

5. 代理模式 - 控制访问

// 代理 - 延迟加载
class ShapeProxy : public Shape {
private:mutable std::unique_ptr<Shape> realShape;ShapeFactory::ShapeType type;public:ShapeProxy(ShapeFactory::ShapeType type) : type(type) {}void draw() const override {if(!realShape) {std::cout << "Loading real shape..." << std::endl;realShape = ShapeFactory::createShape(type);}realShape->draw();}std::string getName() const override {if(!realShape) {return "Proxy for " + std::to_string(type);}return realShape->getName();}
};

6. 外观模式 - 简化复杂操作

// 图形系统外观
class GraphicsSystem {
private:std::vector<std::unique_ptr<Shape>> shapes;public:void addShape(std::unique_ptr<Shape> shape) {shapes.push_back(std::move(shape));}void drawAll() const {std::cout << "\nDrawing all shapes:" << std::endl;for(const auto& shape : shapes) {shape->draw();}}void printAllNames() const {std::cout << "\nAll shape names:" << std::endl;for(const auto& shape : shapes) {std::cout << shape->getName() << std::endl;}}// 创建并添加一个装饰后的复杂形状void addComplexShape(ShapeFactory::ShapeType type, const std::string& color, int borderWidth) {auto shape = ShapeFactory::createShape(type);auto colored = std::make_unique<ColoredShape>(std::move(shape), color);auto bordered = std::make_unique<BorderedShape>(std::move(colored), borderWidth);shapes.push_back(std::move(bordered));}
};

7. 主函数 - 使用示例

int main() {GraphicsSystem system;// 使用工厂创建基本形状auto circle = ShapeFactory::createShape(ShapeFactory::CIRCLE);auto rectangle = ShapeFactory::createShape(ShapeFactory::RECTANGLE);// 使用适配器auto legacyAdapter = std::make_unique<LegacyGraphicsAdapter>("OldCircle");// 使用装饰器auto redTriangle = std::make_unique<ColoredShape>(ShapeFactory::createShape(ShapeFactory::TRIANGLE), "Red");auto borderedRedTriangle = std::make_unique<BorderedShape>(std::move(redTriangle), 5);// 使用代理auto proxy = std::make_unique<ShapeProxy>(ShapeFactory::RECTANGLE);// 添加到系统system.addShape(std::move(circle));system.addShape(std::move(rectangle));system.addShape(std::move(legacyAdapter));system.addShape(std::move(borderedRedTriangle));system.addShape(std::move(proxy));// 使用外观的便捷方法system.addComplexShape(ShapeFactory::CIRCLE, "Blue", 3);// 执行操作system.drawAll();system.printAllNames();return 0;
}

这个示例展示了:

  1. 工厂模式用于创建不同类型的形状对象

  2. 适配器模式使不兼容的LegacyGraphics类能够与系统一起工作

  3. 装饰器模式动态地为形状添加颜色和边框

  4. 代理模式实现延迟加载

  5. 外观模式提供简化的接口来管理复杂的图形系统

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

相关文章:

  • 设计原则和设计模式
  • 浅窥Claude-Prompting for Agents的Talk
  • Go语法:闭包
  • AD方案(OpenLDAP或微软AD)适配信创存在的不足以及可能优化方案
  • 风光储综合能源系统双层优化规划设计【MATLAB模型实现】
  • Android 之 WebView与HTML交互
  • ticdc同步集群部署
  • Java ++i 与 i++ 底层原理
  • 六、Linux核心服务与包管理
  • Unity_数据持久化_IXmlSerializable接口
  • java:判断两个实例(对象)相等
  • 多向量检索:lanchain,dashvector,milvus,vestorsearch,MUVERA
  • RabbitMQ面试精讲 Day 9:优先级队列与惰性队列
  • SQL154 插入记录(一)
  • 十八、Javaweb-day18-前端实战-登录
  • JavaScript 性能优化实战指南:从运行时到用户体验的全面提升​
  • 【openlayers框架学习】十:openlayers中控件的使用
  • 学习笔记《区块链技术与应用》第六天 问答 匿名技术 零知识证明
  • Apple基础(Xcode④-Flutter-Platform Channels)
  • Stream 过滤后修改元素,却意外修改原列表
  • Swift 运算符
  • 【Django】-9- 单元测试和集成测试(上)
  • Android 之 蓝牙通信(4.0 BLE)
  • Redis+Lua的分布式限流器
  • C++编译过程与GDB调试段错误和死锁问题
  • 北邮:LLM强化学习架构Graph-R1
  • C++-二叉树OJ题
  • 【反转字符串中的单词】
  • 从零开始设计一个分布式KV存储:基于Raft的协程化实现
  • 吴恩达【prompt提示词工程】学习笔记