工厂模式通过工厂函数创建对象以解耦客户端代码,首先定义抽象基类Product,再实现具体产品ConcreteProductA和ConcreteProductB,接着编写工厂函数createProduct根据参数返回对应产品的智能指针,最后在main函数中调用工厂获取对象并使用,新增产品时只需修改工厂逻辑,符合开闭原则。

工厂模式是一种常见的创建型设计模式,用来解耦对象的创建过程。在C++中实现一个简单的工厂模式,核心是通过一个工厂类或函数来决定创建哪种具体类型的对象,而不需要在代码中直接使用new操作符硬编码类名。
1. 定义抽象基类(产品接口)
首先定义一个所有具体产品类的共同基类,通常是一个抽象类,包含一个或多个纯虚函数。
示例:class Product {
public:
virtual ~Product() = default;
virtual void use() const = 0;
};
这个Product类作为接口,所有具体产品都要继承它并实现use()方法。
2. 创建具体产品类
从基类派生出多个具体类,每个类代表一种实际的产品。
示例:class ConcreteProductA : public Product {
public:
void use() const override {
std::cout <p>这两个类分别实现了自己的行为,将来由工厂决定创建哪一个。</p><h3>3. 实现工厂类或工厂函数</h3><p>工厂负责根据输入参数创建对应的产品对象。可以使用普通函数,也可以封装成类的静态方法。</p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill8745" title="Model Switcher"><img
src="https://img.php.cn/upload/skill/000/000/081/179222049139243.jpg" alt="Model Switcher" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/skill8745" title="Model Switcher" class="overflowclass">Model Switcher</a>
<p class="overflowclass">根据任务复杂度自动切换不同的AI模型。支持OpenClaw设置中的所有可用模型。当检测到复杂...</p>
</div>
<a rel="nofollow" href="/xiazai/skill8745" title="Model Switcher" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div><font color="#0000FF"><strong>示例:简单工厂函数</strong></font><pre class="brush:php;toolbar:false;">std::unique_ptr<product> createProduct(char type) {
switch (type) {
case 'A':
return std::make_unique<concreteproducta>();
case 'B':
return std::make_unique<concreteproductb>();
default:
return nullptr;
}
}
</concreteproductb></concreteproducta></product>
这里使用std::unique_ptr管理内存,避免手动释放,提升安全性。
4. 使用工厂创建对象
客户端不再直接实例化具体类,而是调用工厂获取对象。
示例:int main() {
auto product1 = createProduct('A');
if (product1) {
product1->use(); // 输出: Using Product A
}
auto product2 = createProduct('B');
if (product2) {
product2->use(); // 输出: Using Product B
}
return 0;
}
这样,新增产品时只需修改工厂逻辑,其他代码无需改动,符合开闭原则。
基本上就这些。这个模式不复杂但容易忽略细节,比如记得基类析构函数设为虚函数,防止资源泄漏。用智能指针配合工厂能大大提升代码的安全性和可维护性。
C++免费学习笔记(深入):立即使用
在学习笔记中,你将探索 C++ 的入门与实战技巧!










