C++设计模式之建造者设计模式

C++建造者设计模式

什么是建造者设计模式

建造者设计模式是一种创建型设计模式,它是一种将复杂对象的分解为多个独立部分的模式,以便于构建对象的过程可以被抽象出来并独立变化。

该模式有什么优缺点

优点

  1. 灵活性:建造者设计模式允许对象的部分以不同的方式进行构建,从而提高了对象的灵活性。
  2. 分离性:建造者设计模式将对象的构建过程与其表示分离开来,使得两者可以独立变化。
  3. 可重用性:建造者设计模式可以将对象的构建过程封装起来,以便在不同的场景下重用。

缺点

  1. 复杂性:建造者设计模式需要定义多个类和接口,这会增加代码的复杂度。
  2. 可读性:建造者设计模式的代码可能不够直观,需要一定的经验才能理解。

如何使用

下面是一个使用C++实现建造者设计模式的例子:

c 复制代码
#include <iostream>  
#include <string>  
#include <vector>  
  
// 定义产品类  
class Product {  
public:  
    void add(std::string part) {  
        parts.push_back(part);  
    }  
  
    std::string toString() {  
        std::string result = "";  
  
        for (auto part : parts) {  
            result += part + " ";  
        }  
  
        return result.substr(0, result.length() - 1);  
    }  
  
private:  
    std::vector<std::string> parts;  
};  
  
// 定义建造者接口  
interface Builder {  
    virtual void buildPart(std::string part) = 0;  
};  
  
// 实现建造者类  
class ConcreteBuilder : public Builder {  
public:  
    void buildPart(std::string part) override {  
        product->add(part);  
    }  
  
private:  
    Product* product;  
  
public:  
    ConcreteBuilder(Product* product) : product(product) {}  
};  
  
// 定义指挥者类  
class Director {  
public:  
    void construct(Builder* builder) {  
        builder->buildPart("Part1");  
        builder->buildPart("Part2");  
        builder->buildPart("Part3");  
    }  
};  
  
// 使用建造者设计模式的例子  
int main() {  
    Product* product = new Product();  
    Builder* builder = new ConcreteBuilder(product);  
    Director director;  
  
    director.construct(builder);  
  
    std::cout << product->toString() << std::endl;  
  
    delete product;  
    delete builder;  
  
    return 0;  
}

在上面的例子中,我们首先定义了一个Product类,它表示要构建的对象。然后我们定义了一个Builder接口,它定义了构建对象的方法。接着我们实现了ConcreteBuilder类,它实现了Builder接口,并将对象的构建过程封装起来。最后我们定义了Director类,它负责指导构建过程。在main函数中,我们创建了一个Product对象和一个ConcreteBuilder对象,并将它们关联起来。然后我们使用Director类来指导构建过程,最终输出构建好的对象。需要注意的是,在使用建造者设计模式时,需要仔细设计接口和类之间的关系,以便正确地构建对象。

相关推荐
红辣椒...1 分钟前
codex+第三方模型
java·服务器·前端
老码观察3 分钟前
设计模式实战解读(八):代理模式——控制访问的隐形中间层
设计模式·代理模式
不会C语言的男孩3 分钟前
C++ Primer Plus 第12章:类和动态内存分配
开发语言·c++
一个做软件开发的牛马12 分钟前
Java 继承与多态:从"是什么"到"能做什么"的设计思维
java·后端
星卯教育tony15 分钟前
CIE中国电子学会2026年3月c++ Python scratch 机器人真题试卷含参考答案
c++·python·scratch·电子学会
不懂的浪漫21 分钟前
05|Netty ByteBuf 源码分析:为什么不用 Java ByteBuffer
java·netty
wapicn9927 分钟前
API接口调试笔记:从注册到第一个数据返回,全流程详解
java·开发语言·python·lua
程序员阿明30 分钟前
flowable集成flowable及其运行示例spring boot后端
java·spring boot·后端
我爱cope33 分钟前
【Agent智能体12 | 反思设计模式-使用外部反馈】
人工智能·设计模式·语言模型·职场和发展
geovindu33 分钟前
python: Bounded Parallelism Pattern
开发语言·python·设计模式·有界并行模式