建造者模式
定义:将一个复杂对象的构造与他的表示分离,是同样的构造过程可以创建不同的表示。可以想象为先创建一个产品的骨架,再拼接他的零件。
特点:(1)各个具体的建造者相互独立,有利于系统的扩展。(2)客户端不必知道产品内部的组成细节,便于控制细节风险。
主要角色 Product,AbstractBuilder,Builder,Director
C++实现
Product.h
#pragma once
#include<string>
using namespace std;
class Product {
public:
Product();
~Product();
void setPartA(string param);
void setPartB(string param);
void setPartC(string param);
void show();
private:
string partA;
string partB;
string partC;
};
Product.cpp
#include"Product.h"
#include<iostream>
using namespace std;
Product::Product() {
}
Product::~Product() {
}
void Product::setPartA(string param) {
this->partA = param;
}
void Product::setPartB(string param) {
this->partB = param;
}
void Product::setPartC(string param) {
this->partC = param;
}
void Product::show() {
cout << "partA:" << partA << " partB:" << partB << " partC:" << partC << endl;
}
Builder.h
#pragma once
#include"Product.h"
class AbstractBuilder {
public:
AbstractBuilder();
virtual ~AbstractBuilder();
virtual void buildPartA(string param) = 0;
virtual void buildPartB(string param) = 0;
virtual void buildPartC(string param) = 0;
virtual void PrepareProduct() = 0;
virtual Product* createProduct() = 0;
};
class Builder :public AbstractBuilder {
public:
Builder();
~Builder();
void buildPartA(string param);
void buildPartB(string param);
void buildPartC(string param);
void PrepareProduct();
Product* createProduct();
private:
Product* curProduct;
};
Builder.cpp
#include"Builder.h"
#include<iostream>
using namespace std;
AbstractBuilder::AbstractBuilder() {
}
AbstractBuilder::~AbstractBuilder() {
}
Builder::Builder() {
}
Builder::~Builder() {
}
void Builder::PrepareProduct() {
cout << "创建一个产品骨架" << endl;
curProduct = new Product();
}
void Builder::buildPartA(string param) {
cout << "正在构造产品A部分" << endl;
curProduct->setPartA(param);
}
void Builder::buildPartB(string param) {
cout << "正在构建产品B部分" << endl;
curProduct->setPartB(param);
}
void Builder::buildPartC(string param) {
cout << "正在构建产品C部分" << endl;
curProduct->setPartC(param);
}
Product* Builder::createProduct() {
return curProduct;
}
Director.h
#pragma once
#include"Builder.h"
class Director {
public:
Director(AbstractBuilder* builder);
~Director();
void construct();
private:
AbstractBuilder* curBuilder;
};
Director.cpp
#include"Director.h"
Director::Director(AbstractBuilder* builder) {
this->curBuilder = builder;
}
Director::~Director() {
}
void Director::construct() {
if (curBuilder == nullptr) return;
curBuilder->PrepareProduct();
curBuilder->buildPartA("A");
curBuilder->buildPartB("B");
curBuilder->buildPartC("C");
}
main.cpp
#include"Director.h"
int main(void) {
AbstractBuilder* builder = new Builder();
Director* director = new Director(builder);
director->construct();
Product* product = builder->createProduct();
product->show();
return 0;
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/9a2456bf187b7ae7183c105c665da32f.png)