builder实现project里面具体复杂对象的实现
Director指定生成哪些复杂对象
打个比方就像去吃鸡公煲,你把菜单(Director)给服务员,厨师(厨师做饭的过程就是builder)根据菜单做饭(project)
builder.h
#ifndef _BUILDER_H
#define _BUILDER_H
#include <iostream>
#include <string>
using namespace std;
class Project
{
public:
Project() {}
~Project() {}
public:
string str1;
string str2;
};
class Builder
{
public:
virtual ~Builder() {}
virtual void BuildStr1() {}
virtual void BuildStr2() {}
protected:
Builder() {
project_ = new Project;
}
public:
Project* project_;
};
class RealBuilder : public Builder
{
public:
RealBuilder() : Builder() {};
virtual ~RealBuilder() {};
void BuildStr1() {
project_->str1 = "string1";
}
void BuildStr2() {
project_->str2 = "string2";
}
};
class Director
{
public:
Director(Builder* build) : builder_(build) {}
Project* Construct() {
builder_->BuildStr1();
builder_->BuildStr2();
return builder_->project_;
}
private:
Builder* builder_;
};
#endif // _BUILDER_H
builder.cpp
#include "builder.h"
int main()
{
Builder* build = new RealBuilder;
Director *con = new Director(build);
Project* project = con->Construct();
cout << project->str1 << endl;
cout << project->str2 << endl;
return 0;
}
编译:make builder
网友评论