生成器模式是一种创建型设计模式,用于分步骤创建复杂对象,从而隐藏构建过程的细节。并且相同的创建代码可以生成不同类型和形式的对象。
什么是复杂对象?
在面向对象的编程中,实际体现的就是一个类的构造函数。有这么一个类,它有很多成员变量,成员变量中有简单的类型对象,也有其他用户自定义的类型对象。需要在构造函数中对这些成员变量进行初始化工作。构造函数带了很多参数,用于不同成员变量的初始化。
解决的问题
创建这样的对象,通常要传递很多参数,其中有很多是没用的。并且要在构造函数里做很多if判断。
类图
示例代码
#include <iostream>
#include <string>
// 1. 产品 - 计算机
class Computer {
public:
void setMotherboard(const std::string& motherboard) {
motherboard_ = motherboard;
}
void setCPU(const std::string& cpu) {
cpu_ = cpu;
}
void setMemory(const std::string& memory) {
memory_ = memory;
}
void setStorage(const std::string& storage) {
storage_ = storage;
}
void display() const {
std::cout << "Computer Configuration:" << std::endl;
std::cout << "Motherboard: " << motherboard_ << std::endl;
std::cout << "CPU: " << cpu_ << std::endl;
std::cout << "Memory: " << memory_ << std::endl;
std::cout << "Storage: " << storage_ << std::endl;
}
private:
std::string motherboard_;
std::string cpu_;
std::string memory_;
std::string storage_;
};
// 2. 生成器接口
class ComputerBuilder {
public:
virtual void buildMotherboard() = 0;
virtual void buildCPU() = 0;
virtual void buildMemory() = 0;
virtual void buildStorage() = 0;
virtual Computer getResult() = 0;
};
// 3. 具体生成器 - 高性能计算机生成器
class HighPerformanceComputerBuilder : public ComputerBuilder {
public:
void buildMotherboard() override {
computer_.setMotherboard("High-Performance Motherboard");
}
void buildCPU() override {
computer_.setCPU("High-Performance CPU");
}
void buildMemory() override {
computer_.setMemory("High-Performance Memory");
}
void buildStorage() override {
computer_.setStorage("SSD Storage");
}
Computer getResult() override {
return computer_;
}
private:
Computer computer_;
};
// 4. 具体生成器 - 普通计算机生成器
class RegularComputerBuilder : public ComputerBuilder {
public:
void buildMotherboard() override {
computer_.setMotherboard("Regular Motherboard");
}
void buildCPU() override {
computer_.setCPU("Regular CPU");
}
void buildMemory() override {
computer_.setMemory("Regular Memory");
}
void buildStorage() override {
computer_.setStorage("HDD Storage");
}
Computer getResult() override {
return computer_;
}
private:
Computer computer_;
};
// 5. 指导者
class ComputerDirector {
public:
Computer buildComputer(ComputerBuilder& builder) {
builder.buildMotherboard();
builder.buildCPU();
builder.buildMemory();
builder.buildStorage();
return builder.getResult();
}
};
int main() {
// 使用生成器模式构建高性能计算机
HighPerformanceComputerBuilder highPerformanceBuilder;
ComputerDirector director;
Computer highPerformanceComputer = director.buildComputer(highPerformanceBuilder);
highPerformanceComputer.display();
std::cout << std::endl;
// 使用生成器模式构建普通计算机
RegularComputerBuilder regularBuilder;
Computer regularComputer = director.buildComputer(regularBuilder);
regularComputer.display();
return 0;
}