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

C++建造者设计模式

在这里插入图片描述

什么是建造者设计模式

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

该模式有什么优缺点

优点

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

缺点

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

如何使用

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

早睡的叶子

你的鼓励就是我的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值