标签:
建造者模式:
优点:
1.隔离了构建的步骤和具体的实现,为产品的具体实现提供了灵活性
2.封装和抽象了每个步骤的实现,实现了依赖倒置原则
3.封装了具体的步骤,减少了代码冗余
缺点:
1.要求构建的产品不能剧烈变化
代码示例:
Builer.h
#ifndef BULIDER_H #define BULIDER_H class Builder { public: virtual void buildHead() = 0; virtual void buildBody() = 0; virtual void buildLeftArm() = 0; virtual void buildRightArm() = 0; virtual void buildLeftLeg() = 0; virtual void buildRightLeg() = 0; }; class ThinBuilder : public Builder { public: void buildHead(); void buildBody(); void buildLeftArm(); void buildRightArm(); void buildLeftLeg(); void buildRightLeg(); }; class FatBuilder : public Builder { public: void buildHead(); void buildBody(); void buildLeftArm(); void buildRightArm(); void buildLeftLeg(); void buildRightLeg(); }; class Director { public: Director(Builder *builder); void setBuilder(Builder *builder); void creadte(); private: Builder *m_builder; }; #endif // BULIDER_H
#include "bulider.h" #include <iostream> void ThinBuilder::buildHead() { std::cout << "build thin Head" << std::endl; } void ThinBuilder::buildBody() { std::cout << "build thin Body" << std::endl; } void ThinBuilder::buildLeftArm() { std::cout << "build thin LeftArm" << std::endl; } void ThinBuilder::buildRightArm() { std::cout << "build thin RightArm" << std::endl; } void ThinBuilder::buildLeftLeg() { std::cout << "build thin LeftLeg" << std::endl; } void ThinBuilder::buildRightLeg() { std::cout << "build thin RightLeg" << std::endl; } void FatBuilder::buildHead() { std::cout << "build fat Head" << std::endl; } void FatBuilder::buildBody() { std::cout << "build fat Body" << std::endl; } void FatBuilder::buildLeftArm() { std::cout << "build fat LeftArm" << std::endl; } void FatBuilder::buildRightArm() { std::cout << "build fat RightArm" << std::endl; } void FatBuilder::buildLeftLeg() { std::cout << "build fat LeftLeg" << std::endl; } void FatBuilder::buildRightLeg() { std::cout << "build fat RightLeg" << std::endl; } Director::Director(Builder *builder) :m_builder(builder) { } void Director::setBuilder(Builder *builder) { m_builder = builder; } void Director::creadte() { m_builder->buildHead(); m_builder->buildBody(); m_builder->buildLeftArm(); m_builder->buildRightArm(); m_builder->buildLeftLeg(); m_builder->buildRightLeg(); }
#include <iostream> #include "bulider.h" int main() { FatBuilder fatBuilder; Director director(&fatBuilder); director.creadte(); std::cout << std::endl; ThinBuilder thisBuilder; director.setBuilder(&thisBuilder); director.creadte(); return 0; }
标签:
原文地址:http://blog.csdn.net/fu1201520/article/details/51330581