提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
提示:这里可以添加本文要记录的大概内容:
软件系统中,有时候面临着一个复杂对象的创建工作,其通常由各个部分的子对象用一定算法构成。这个对象的各个部分面临着剧烈的变化,但是将他们组合在一起的算法却相对稳定。有点类似模板方法模式,整个构建的流程是稳定,但是构建的每一步是不一样的。
提示:以下是本篇文章正文内容,下面案例可供参考
一、原始代码
class House
{
public:
void Init()
{
this->BuildPart1();
for (size_t i = 0; i < 4; i++)
{
this->BuildPart2();
}
bool flag = this->BuildPart3();
if (flag)
{
this->BuildPart4();
}
this->BuildPart5();
}
virtual ~House() {}
protected:
virtual void BuildPart1() = 0;
virtual void BuildPart2() = 0;
virtual bool BuildPart3() = 0;
virtual void BuildPart4() = 0;
virtual void BuildPart5() = 0;
};
class StoneHouse : House
{
protected:
virtual void BuildPart1()
{
}
virtual void BuildPart2()
{
}
virtual bool BuildPart3()
{
}
virtual void BuildPart4() {}
virtual void BuildPart5() {}
};
int main()
{
House *house = new StoneHouse();
house->Init();
}
二、优化空间
将流程部分(Init函数)提出去放到HouseDirector里面去,将具体方法提出去放到HouseBuilder里。
class House
{
public:
virtual ~House() {}
protected:
virtual void BuildPart1() = 0;
virtual void BuildPart2() = 0;
virtual bool BuildPart3() = 0;
virtual void BuildPart4() = 0;
virtual void BuildPart5() = 0;
};
class HouseBuilder
{
public:
HouseBuilder(House* pHouse){this->pHouse = pHouse;s}
House *GetResult() { return pHouse; }
virtual ~HouseBuilder() {}
protected:
House *pHouse;
virtual void BuildPart1() = 0;
virtual void BuildPart2() = 0;
virtual bool BuildPart3() = 0;
virtual void BuildPart4() = 0;
virtual void BuildPart5() = 0;
};
class StoneHouse : House
{
};
class StoneHouseBuilder : HouseBuilder
{
protected:
virtual void BuildPart1()
{
//pHouse->...
}
virtual void BuildPart2()
{
//pHouse->...
}
virtual bool BuildPart3()
{
//pHouse->...
}
virtual void BuildPart4() {}
virtual void BuildPart5() {}
};
class HouseDirector
{
public:
HouseBuilder *pHouseBuilder;
HouseDirector(HouseBuilder *pHouseBuilder){this->pHouseBuilder = pHouseBuilder;}
House *Constuct()
{
pHouseBuilder->BuildPart1();
for (size_t i = 0; i < 4; i++)
{
pHouseBuilder->BuildPart2();
}
bool flag = pHouseBuilder->BuildPart3();
if (flag)
{
pHouseBuilder->BuildPart4();
}
pHouseBuilder->BuildPart5();
return pHouseBuilder->GetHouse();
}
}
int main()
{
House *house = new StoneHouse();
HouseBuilder *builder = new StoneHouseBuilder(house);
HouseDirector *director = new HouseDirector(builder);
director->Constuct();
}