3.建造模式(Builder)
注:图片来源于 https://www.cnblogs.com/-saligia-/p/10216752.html
建造模式UML图解析:
代码:
Director.h
// // Created by DELL on 2019/10/15. // #ifndef BUILDER_DIRECTOR_H #define BUILDER_DIRECTOR_H #include "Builder.h" class Director { public: explicit Director(PhoneBuilder* pb) { builder = pb; } void BuildPlan() { builder->BuildOS(); builder->BuildShape(); builder->BuildMemory(); builder->ShowDetail(); } private: PhoneBuilder* builder; }; #endif //BUILDER_DIRECTOR_H
Builder.h
// // Created by DELL on 2019/10/15. // #ifndef BUILDER_BUILDER_H #define BUILDER_BUILDER_H #include "Product.h" class PhoneBuilder { public: virtual void BuildOS() = 0; virtual void BuildShape() = 0; virtual void BuildMemory() = 0; virtual void ShowDetail() = 0; }; class HUAWEIBuilder : public PhoneBuilder { public: HUAWEIBuilder() { phone = new Phone(); } void BuildOS() override { phone->SetOS("HMOS"); } void BuildShape() override { phone->SetShape("6.2inch"); } void BuildMemory() override { phone->SetMemory("8G"); } void ShowDetail() override { phone->showDetail(); } private: Phone* phone; }; class OPPOBuilder : public PhoneBuilder { public: OPPOBuilder() { phone = new Phone(); } void BuildOS() override { phone->SetOS("ColorOS"); } void BuildShape() override { phone->SetShape("6.5inch"); } void BuildMemory() override { phone->SetMemory("6G"); } void ShowDetail() override { phone->showDetail(); } private: Phone* phone; }; #endif //BUILDER_BUILDER_H
Product.h
// // Created by DELL on 2019/10/15. // #ifndef BUILDER_PRODUCT_H #define BUILDER_PRODUCT_H #include <string> #include <utility> #include <iostream> //产品类-手机 class Phone { public: Phone() : phone_os("Android"), phone_shape("5 inch"), phone_memory("4G"){} //set成员函数用于设置private成员变量 void SetOS(std::string os) { phone_os = std::move(os); } void SetShape(std::string shape) { phone_shape = std::move(shape); } void SetMemory(std::string memory) { phone_memory = std::move(memory); } void showDetail() { std::cout << phone_os << " " << phone_shape << " " << phone_memory << std::endl; } private: std::string phone_os; std::string phone_shape; std::string phone_memory; }; #endif //BUILDER_PRODUCT_H
用户 main.cpp
#include <iostream> #include "Director.h" #include "Builder.h" using namespace std; int main() { PhoneBuilder* hw = new HUAWEIBuilder(); auto* dr1 = new Director(hw); dr1->BuildPlan(); PhoneBuilder* op = new OPPOBuilder(); auto* dr2 = new Director(op); dr2->BuildPlan(); return 0; }
注:工厂模式与建造模式最大区别在于:工厂模式关注如何获取实例对象,而建造模式关注如何建造实例对象。
工厂模式直接产出产品,不关注细节,而建造模式关注的是产品的细节,关心如何构造产品的每个细节进而组合成完整产品。
以上是两种模式的区别。