目录
C++设计模式-生成器(Builder)
一、意图
二、适用性
三、结构
四、参与者
五、代码
C++设计模式-生成器(Builder)
一、意图
将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。
二、适用性
- 当创建复杂对象的算法应该独立于该对象的组成部分以及它们的装配方式时。
-
当构造过程必须允许被构造的对象有不同的表示时。
三、结构
四、参与者
- Builder
为创建一个Product对象的各个部件指定抽象接口。
- ConcreteBuilder
实现Builder的接口以构造和装配该产品的各个部分。
定义并明确它所创建的表示。
提供一个检索产品的接口。
- Director
构造一个使用Builder接口的对象
- Product
表示被构造的复杂对象。ConcreteBuilder创建该产品的内部表示并定义它的装配过程。
包含定义组成部件的类,包括将这些部件装配成最终产品的接口。
五、代码
#include<iostream>
using namespace std;
class Product {
public:
void SetPartOne(string TempPartOne) {
PartOne = TempPartOne;
cout << "Set Part One: " << PartOne << endl;
}
void SetPartTwo(string TempPartTwo) {
PartTwo = TempPartTwo;
cout << "Set Part Two: " << PartTwo << endl;
}
void SetPartThree(string TempPartThree) {
PartThree = TempPartThree;
cout << "Set Part Three: " << PartThree << endl;
}
private:
string PartOne;
string PartTwo;
string PartThree;
};
class Builder {
public:
Product GetProduct() {
return product;
}
virtual void BuildPartOne() = 0;
virtual void BuildPartTwo() = 0;
virtual void BuildPartThree() = 0;
protected:
Product product;
};
class ProductOneBuilder : public Builder {
public:
void BuildPartOne() {
product.SetPartOne("Product One's Part One");
}
void BuildPartTwo() {
product.SetPartTwo("Product One's Part Two");
}
void BuildPartThree() {
product.SetPartThree("Product One's Part Three");
}
};
class ProductTwoBuilder : public Builder {
public:
void BuildPartOne() {
product.SetPartOne("Product Two's Part One");
}
void BuildPartTwo() {
product.SetPartTwo("Product Two's Part Two");
}
void BuildPartThree() {
product.SetPartThree("Product Two's Part Three");
}
};
class Director {
public:
Director() :builder(nullptr) {}
void SetBuilder(Builder* TempBuilder) {
this->builder = TempBuilder;
}
Product ConstructProduct() {
builder->BuildPartOne();
builder->BuildPartTwo();
builder->BuildPartThree();
return builder->GetProduct();
}
private:
Builder* builder;
};
int main() {
Builder* builder;
Director* director = new Director;
Product product;
cout << "*** *** Construct Product One *** ***" << endl;
builder = new ProductOneBuilder;
director->SetBuilder(builder);
product = director->ConstructProduct();
delete builder;
cout << "*** *** Construct Product Two *** ***" << endl;
builder = new ProductTwoBuilder;
director->SetBuilder(builder);
product = director->ConstructProduct();
delete builder;
delete director;
return 0;
}