在 C++面向对象编程 中,工厂模式 是一种非常经典且实用的设计模式。它属于创建型模式,主要用于解耦对象的创建与使用过程。本教程将用通俗易懂的方式,手把手带你实现一个完整的 C++工厂模式 示例,即使你是编程小白也能轻松上手!

工厂模式的核心思想是:不直接使用 new 关键字创建对象,而是通过一个“工厂”类来负责创建具体对象。这样做的好处是:
一个典型的工厂模式包含以下部分:
假设我们要开发一个图形绘制程序,支持绘制圆形(Circle)和矩形(Rectangle)。我们使用 工厂方法模式 来实现。
// Shape.h#ifndef SHAPE_H#define SHAPE_H#include <iostream>class Shape {public: virtual ~Shape() = default; virtual void draw() const = 0; // 纯虚函数,定义绘图接口};#endif // SHAPE_H// Circle.h#ifndef CIRCLE_H#define CIRCLE_H#include "Shape.h"class Circle : public Shape {public: void draw() const override { std::cout << "Drawing a Circle" << std::endl; }};#endif // CIRCLE_H// Rectangle.h#ifndef RECTANGLE_H#define RECTANGLE_H#include "Shape.h"class Rectangle : public Shape {public: void draw() const override { std::cout << "Drawing a Rectangle" << std::endl; }};#endif // RECTANGLE_H// ShapeFactory.h#ifndef SHAPE_FACTORY_H#define SHAPE_FACTORY_H#include "Shape.h"#include "Circle.h"#include "Rectangle.h"#include <memory>#include <string>class ShapeFactory {public: static std::unique_ptr<Shape> createShape(const std::string& type) { if (type == "Circle") { return std::make_unique<Circle>(); } else if (type == "Rectangle") { return std::make_unique<Rectangle>(); } else { std::cerr << "Unknown shape type: " << type << std::endl; return nullptr; } }};#endif // SHAPE_FACTORY_H// main.cpp#include "ShapeFactory.h"int main() { auto circle = ShapeFactory::createShape("Circle"); auto rectangle = ShapeFactory::createShape("Rectangle"); if (circle) circle->draw(); // 输出: Drawing a Circle if (rectangle) rectangle->draw(); // 输出: Drawing a Rectangle return 0;}在上面的例子中,我们使用了 std::unique_ptr 来管理对象生命周期。这是现代 C++ 的最佳实践,可以自动释放内存,避免内存泄漏。
✅ 优势:
🎯 适用场景:
通过本教程,你已经掌握了 C++工厂模式 的基本原理和实现方法。作为 C++面向对象编程 中的重要 设计模式,工厂模式能显著提升代码的可维护性和扩展性。记住,工厂方法模式 的核心是“将对象的创建委托给专门的工厂类”,从而实现高内聚、低耦合的软件架构。
动手试试吧!你可以尝试添加三角形(Triangle)类型,看看如何在不修改客户端代码的情况下扩展功能。
本文由主机测评网于2025-12-12发表在主机测评网_免费VPS_免费云服务器_免费独立服务器,如有疑问,请联系我们。
本文链接:https://www.vpshk.cn/2025126518.html