//电脑组装:显示器、鼠标、键盘、主机(主机又包括cpu、显卡、主板等)
// 1.找到店铺老板告诉需求
// 2.客服安排技术员工组装
// 3.产品组装完成
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class AbstractProduct {
public:
virtual void SetDisplayer(string displayer) = 0;
virtual void SetMouse(string mouse) = 0;
virtual void SetKeyBoard(string keyBoard) = 0;
virtual void SetHost(string host) = 0;
virtual void Show() = 0;
// vector<string> m_list; //电脑清单
};
class Computer : public AbstractProduct {
void SetDisplayer(string displayer) { m_list.push_back(displayer); }
void SetMouse(string mouse) { m_list.push_back(mouse); }
void SetKeyBoard(string keyBoard) { m_list.push_back(keyBoard); }
void SetHost(string host) { m_list.push_back(host); }
void Show() {
cout << "组装电脑配置:" << endl;
for (auto v : m_list) {
cout << v << endl;
}
}
vector<string> m_list; //电脑清单
};
//抽象建造者
class AbstarctBuilder {
public:
AbstarctBuilder() : product(new Computer) {}
virtual void BuildDisplayer(string displayer) = 0;
virtual void BuildMouse(string mouse) = 0;
virtual void BuildKeyBoard(string keyBoard) = 0;
virtual void BuildHost(string host) = 0;
AbstractProduct* GetProduct() { return product; }
protected:
AbstractProduct* product;
};
//具体建造者:技术人员
class ConcreteBuilder : public AbstarctBuilder {
public:
virtual void BuildDisplayer(string displayer) {
product->SetDisplayer(displayer);
}
void BuildMouse(string mouse) { product->SetMouse(mouse); }
void BuildKeyBoard(string keyBoard) { product->SetKeyBoard(keyBoard); }
void BuildHost(string host) { product->SetHost(host); }
};
//指挥者
class Director {
public:
Director(AbstarctBuilder* pBuilder) : pBuilder(pBuilder) {}
AbstractProduct* Construct(string displayer,
string mouse,
string keyBoard,
string host) {
pBuilder->BuildDisplayer(displayer);
pBuilder->BuildMouse(mouse);
pBuilder->BuildKeyBoard(keyBoard);
pBuilder->BuildHost(host);
return pBuilder->GetProduct();
}
private:
AbstarctBuilder* pBuilder;
};
int main() {
AbstarctBuilder* pB = new ConcreteBuilder;
Director* pD = new Director(pB);
AbstractProduct* pC =
pD->Construct("华为显示器", "牧马人鼠标", "雷蛇键盘", "外星人");
pC->Show();
return 0;
}
C++建造者模式(4)
最新推荐文章于 2024-08-21 18:16:36 发布