生成器模式是创建型模式的一种,生成器模式主要是解决在大类创建对象初始化的复杂的问题。将一个复杂类的创建拆分成几个部分,再根据具体需求创建初始对象,而不必每次都创建所有的部分。在需要创建包含有不同内容的对象的时候,可以通过生成器类,生成器类可以创建多个,就可以生成对于的对象。
使用场景:
1、当要使用的类在生成的时候有哦多个不同的可选参数或者模块,为了避免构造函数过大可以使用生成器模式。
2、当要是的组成部分可能有不同的属性的时候可以使用生成器模式。
使用方式:
1、明确定义步骤,确保包含了所有的生成形式。
2、在基本生成器的接口中声明步骤。
代码:
int main()
{std::cout << "欢迎东哥来到设计模式的世界!\n";SCCarBuilder* builder = new SCCarSpecificBuilder();SCarManage* manger = new SCarManage();manger->setBuilder(builder);manger->createCarPart1();SCCarProduct* product = builder->m_SCCarProduct;cout << product->part1 << " : " << product->part2 << " : "<< product->part3 << endl;SCCarBuilder* builder2 = new SCCarSpecificBuilder();SCarManage* manger2 = new SCarManage();manger2->setBuilder(builder2);manger2->createCarPart123();SCCarProduct* product2 = builder2->m_SCCarProduct;cout << product2->part1 << " : " << product2->part2 << " : " << product2->part3 << endl;
}
#pragma once
#include <string>using namespace std;
class SCCarProduct //需要初始化的大类
{
public:SCCarProduct() {};~SCCarProduct() {};string part1 = " ";string part2 = " ";string part3 = " ";
};class SCCarBuilder { //生成器父类类
public:SCCarBuilder();~SCCarBuilder();virtual bool createPart1();virtual bool createPart2();virtual bool createPart3();SCCarProduct* m_SCCarProduct = nullptr;
};class SCCarSpecificBuilder:public SCCarBuilder { //具体的生成器类,实现了每一部分的实现public:SCCarSpecificBuilder();~SCCarSpecificBuilder();bool createPart1();bool createPart2();bool createPart3();
};class SCarManage { //主管类,可要可不要,用于协助生成器类生成具体的复杂类public:SCarManage();~SCarManage();void setBuilder(SCCarBuilder* bulider) { m_builder = bulider; };void createCarPart1();void createCarPart2();void createCarPart3();void createCarPart123();SCCarBuilder* m_builder = nullptr;};
#include "ShengChengQi.h"SCCarBuilder::SCCarBuilder()
{
}SCCarBuilder::~SCCarBuilder()
{
}bool SCCarBuilder::createPart1()
{return false;
}bool SCCarBuilder::createPart2()
{return false;
}bool SCCarBuilder::createPart3()
{return false;
}SCCarSpecificBuilder::SCCarSpecificBuilder()
{m_SCCarProduct = new SCCarProduct();
}SCCarSpecificBuilder::~SCCarSpecificBuilder()
{
}bool SCCarSpecificBuilder::createPart1()
{this->m_SCCarProduct->part1 = "高端模块:黄金外壳,碳纤维轮胎";return true;
}bool SCCarSpecificBuilder::createPart2()
{this->m_SCCarProduct->part2 = "中端模块:精装外壳,橡胶轮胎";return true;
}bool SCCarSpecificBuilder::createPart3()
{this->m_SCCarProduct->part3 = "低端模块:普通外壳,塑料轮胎";return true;
}SCarManage::SCarManage()
{
}SCarManage::~SCarManage()
{
}void SCarManage::createCarPart1()
{m_builder->createPart1();
}void SCarManage::createCarPart2()
{m_builder->createPart2();
}void SCarManage::createCarPart3()
{m_builder->createPart3();
}void SCarManage::createCarPart123()
{m_builder->createPart1();m_builder->createPart2();m_builder->createPart3();
}