首先先大体了解一下,建造者模式是什么意思,它是怎么实现的?
建造者模式主要用于构建复杂问题
建造者模式是一种对象创建型模式之一,用来隐藏复合对象的创建过程,它把复合对象的创建过程加以抽象,通过子类继承和重载的方式,动态地创建具有复合属性的对象。
建造者模式主要基于四个核⼼类实现:
思维导图
#include
#include
#include
//构建电脑需要的零件
class Computer
{
public:
Computer(){}
void setBoard(const std::string &board)
{
_board = board;
}
void setDisplay(const std::string &display)
{
_display = display;
}
void showParamaters()//最终终端输出
{
std::string param = "Computer Paramaters:\n";
param += "\tBoard:"+_board + "\n";
param += "\tDisplay:"+_display + "\n";
param += "\tOs:"+_os + "\n";
std::cout << param << std::endl;
}
virtual void setOs() = 0;//纯虚函数
protected:
std::string _board;//主板
std::string _display;//显示器
std::string _os;//操作系统
};
class MacBook :public Computer
{
public:
void setOs()override
{
_os = "Mac OS X12";
}
};
class Builder
{
public:
virtual void buildBoard(const std::string &board) = 0;//纯虚函数
virtual void buildDisplay(const std::string &display) = 0;
virtual void buildOs() = 0;
virtual std::shared_ptr<Computer> build() = 0;//定义了一个Computer智能指针对象
};
class MacBookBuilder : public Builder
{
public:
MacBookBuilder():_computer(new MacBook()){}
void buildBoard(const std::string& board)
{
_computer->setBoard(board);
}
void buildDisplay(const std::string& display)
{
_computer->setDisplay(display);
}
void buildOs()
{
_computer->setOs();
}
std::shared_ptr<Computer> build()
{
return _computer;
}
private:
std::shared_ptr<Computer> _computer;
};
//指导者
class Director
{
public:
Director(Builder* builder):_builder(builder){}
void construct(const std::string &board,const std::string &display)
{
_builder->buildBoard(board);
_builder->buildDisplay(display);
_builder->buildOs();
}
private:
std::shared_ptr<Builder> _builder;
};
int main()
{
Builder *builder = new MacBookBuilder();
std::unique_ptr<Director> director(new Director(builder));
director->construct("华硕主板","三星显示器");
std::shared_ptr<Computer> computer = builder->build();
computer->showParamaters();
return 0;
}