- 主要用于“分步骤构建一个复杂的对象”。其中“分步骤”是一个稳定的算法,而复杂对象的各个部分则经常变化。
软件系统中面临着“一个负责对象”的创建工作,其通常由各个部分的子对象用一定的算法构成;由于需求的变化,这个复杂对象的各个部分经常面临着剧烈的变化,但是将他们组合在一起的算法却相对稳定。
将一个复杂对象的构建与其表示分离,使得同样的构建过程(稳定)可以创建不同的表示(变化)。
class House{
public:
void Init(){
this->BuildPart1();
for(int 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 void BuildPart3() = 0;
virtual void BuildPart4() = 0;
virtual void BuildPart5() = 0;
};
class StoneHouse : public House{
protected:
virtual void BuildPart1(){}
virtual void BuildPart2(){}
virtual void BuildPart3(){}
virtual void BuildPart4(){}
virtual void BuildPart5(){}
};
int main(){
House* pHouse = new StoneHouse();
pHouse->Init();
}
class House{
//...
};
class HouseBuilder{
public:
Hosue* GetResult(){
return pHouse;
}
virtual ~HouseBuilder(){}
protected:
House* pHouse;
virtual void BuildPart1() = 0;
virtual void BuildPart2() = 0;
virtual void BuildPart3() = 0;
virtual void BuildPart4() = 0;
virtual void BuildPart5() = 0;
};
class HouseDirecotr{
public:
HouseBuilder* pHouseBuilder;
HouseDirecotr(HouseBuilder* houseBuilder) : pHouseBuilder(houseBuilder){}
House* Construct(){
pHouseBuilder->BuildPart1();
for(int i = 0; i < 4; i++){
pHouseBuilder->BuildPart2();
}
bool flag = pHouseBuilder->BuildPart3();
if(flag){
pHouseBuilder->BuildPart4();
}
pHouseBuilder->BuildPart5();
return pHouseBuilder->GetResult();
}
};
class StoneHouse : public House{
};
class StoneHouseBuilder : public HouseBuilder{
protected:
virtual void BuildPart1(){
pHouse->Part1 = ...;
}
virtual void BuildPart2(){}
virtual void BuildPart3(){}
virtual void BuildPart4(){}
virtual void BuildPart5(){}
};