设计模式读书笔记:Builder(建造者)
2015-07-03 11:11:52
意图:
将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。
结构图:来自《23种设计模式 - 郗晓勇》
实现:https://github.com/panshiqu/patterns/tree/master/Builder
Product
#include <iostream>
namespace NS_BUILDER {
class Product {
public:
Product() : _color("none"), _size("none") {}
virtual ~Product() {}
void printSelf(void)
{
std::cout << "Build color: " << _color << " size: " << _size << std::endl;
}
void setColor(std::string color) { _color = color; }
void setSize(std::string size) { _size = size; }
private:
std::string _color;
std::string _size;
};
} /* namespace NS_BUILDER */
Builder
#include <iostream>
namespace NS_BUILDER {
class Builder {
public:
Builder() {}
virtual ~Builder() {}
virtual void setColor(std::string color) = 0;
virtual void setSize(std::string size) = 0;
};
} /* namespace NS_BUILDER */
ConcreteBuilderA
#include "Product.h"
#include "Builder.h"
namespace NS_BUILDER {
class ConcreteBuilderA : public Builder
{
public:
ConcreteBuilderA()
{
_product = new Product();
}
virtual ~ConcreteBuilderA() {}
virtual void setColor(std::string color)
{
// do nothing
}
virtual void setSize(std::string size)
{
_product->setSize(size);
}
Product *getIgnoreColorProduct(void)
{
return _product;
}
private:
Product *_product;
};
} /* namespace NS_BUILDER */
ConcreteBuilderB
#include "Product.h"
#include "Builder.h"
namespace NS_BUILDER {
class ConcreteBuilderB : public Builder
{
public:
ConcreteBuilderB()
{
_product = new Product();
}
virtual ~ConcreteBuilderB() {}
virtual void setColor(std::string color)
{
_product->setColor(color);
}
virtual void setSize(std::string size)
{
_product->setSize(size);
}
Product *getCareColorProduct(void)
{
return _product;
}
private:
Product *_product;
};
} /* namespace NS_BUILDER */
Director
namespace NS_BUILDER {
class Builder;
class Director {
public:
Director(Builder *builder) : _builder(builder) {}
virtual ~Director() {}
void Build(void);
private:
Builder *_builder;
};
} /* namespace NS_BUILDER */
#include "Director.h"
#include "Builder.h"
namespace NS_BUILDER {
void Director::Build(void)
{
// 可能配置中读出来的属性
_builder->setColor("red");
_builder->setSize("big");
}
} /* namespace NS_BUILDER */
main
#include "Builder/Director.h"
#include "Builder/ConcreteBuilderA.h"
#include "Builder/ConcreteBuilderB.h"
#include "Builder/Product.h"
using namespace NS_BUILDER;
int main(void)
{
ConcreteBuilderB *builder = new ConcreteBuilderB();
Director *director = new Director(builder);
director->Build();
Product *product = builder->getCareColorProduct();
product->printSelf();
delete builder;
delete director;
delete product;
}
附加: