设计模式——建造者模式/生成器模式(C++实现)

设计模式——建造者模式/生成器模式(C++实现)

设计模式——建造者模式/生成器模式(C++实现)

 #include <iostream>
#include <string> using namespace std; class STProduct
{
public:
void setA(string str)
{
m_a = str;
} void setB(string str)
{
m_b = str;
} void setC(string str)
{
m_c = str;
} void Show()
{
cout<< "Product: "<< m_a<< "!\t"<< m_b<< "!\t"<< m_c<< endl;
} private:
string m_a;
string m_b;
string m_c;
}; class STBuilder
{
public:
STBuilder()
{
m_pstProduct = new STProduct();
}
virtual ~STBuilder()
{
delete m_pstProduct;
} virtual void BuildPartA() = ;
virtual void BuildPartB() = ;
virtual void BuildPartC() = ; virtual STProduct* GetResult()
{
return m_pstProduct;
} STProduct* m_pstProduct;
}; class STConcreteBuilder: public STBuilder
{
public:
virtual void BuildPartA()
{
m_pstProduct->setA("A Style");
} virtual void BuildPartB()
{
m_pstProduct->setB("B Style");
} virtual void BuildPartC()
{
m_pstProduct->setC("C Style");
}
}; class STDirector
{
public:
~STDirector()
{
delete m_pstBuilder;
} void SetBuilder(STBuilder* pstTmpBuilder)
{
m_pstBuilder = pstTmpBuilder;
} STProduct* Construct()
{
m_pstBuilder->BuildPartA();
m_pstBuilder->BuildPartB();
m_pstBuilder->BuildPartC(); return m_pstBuilder->GetResult();
} STBuilder* m_pstBuilder;
}; int main(int argc, char* argv[])
{
STBuilder* pstBuilder = new STConcreteBuilder(); STDirector* pstDirector = new STDirector();
pstDirector->SetBuilder(pstBuilder); STProduct* pstProduct = pstDirector->Construct();
cout<< "Show.................."<< endl;
pstProduct->Show(); return ;
}
//////////////////////////////////////
[root@ ~/learn_code/design_pattern/10_builder]$ ./builder
Show..................
Product: A Style! B Style! C Style

参考:http://design-patterns.readthedocs.io/zh_CN/latest/creational_patterns/builder.html

上一篇:服务器小白的我,是如何将 node+mongodb 项目部署在服务器上并进行性能优化的


下一篇:thinkphp 单图上传组建成数组然后追加到一个字段