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类来指导构建过程,最终输出构建好的对象。需要注意的是,在使用建造者设计模式时,需要仔细设计接口和类之间的关系,以便正确地构建对象。

相关推荐
遇见你...6 分钟前
A01-Spring概述
java·后端·spring
Via_Neo2 小时前
JAVA中以2为底的对数表示方式
java·开发语言
野生技术架构师3 小时前
一线大厂Java面试八股文全栈通关手册(含源码级详解)
java·开发语言·面试
廋到被风吹走3 小时前
【AI】Codex 多语言实测:Python/Java/JS/SQL 效果横评
java·人工智能·python
tERS ERTS4 小时前
MySQL中查看表结构
java
坊钰4 小时前
Java 死锁问题及其解决方案
java·开发语言·数据库
于先生吖4 小时前
SpringBoot+MQTT 无人健身房智能管控系统源码实战
java·spring boot·后端
仍然.4 小时前
算法题目---模拟
java·javascript·算法
wefly20175 小时前
纯前端架构深度解析:jsontop.cn,JSON 格式化与全栈开发效率平台
java·前端·python·架构·正则表达式·json·php
史蒂芬_丁5 小时前
Qt, C++数据类型扩展问题
数据库·c++·qt