注:图片来源于 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); void Show() { builder->build(); builder->ShowDetail(); } private: PhoneBuilder* builder; }; Director::Director(PhoneBuilder *pb) { builder = pb; } #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 build() = 0; virtual void ShowDetail() = 0; }; class HUAWEIBuilder : public PhoneBuilder { public: HUAWEIBuilder() { phone = new Phone(); } void build() override { phone->setDetail("HM OS", "刘海屏", "8G"); } void ShowDetail() override { phone->showDetail(); } private: Phone* phone; }; class OPPOBuilder : public PhoneBuilder { public: OPPOBuilder() { phone = new Phone(); } void build() override { phone->setDetail("Color OS", "全面屏", "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("刘海屏"), phone_memory("4G"){} void setDetail(std::string os, std::string shape, std::string memory) { phone_os = std::move(os); phone_shape = std::move(shape); 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->Show(); PhoneBuilder* op = new OPPOBuilder(); auto* dr2 = new Director(op); dr2->Show(); return 0; }