1.工厂模式(Factory Method)
注:图片来源于 https://www.cnblogs.com/-saligia-/p/10216752.html
工厂UML图解析:
工厂模式:client用户需要三步:
1.创建工厂;
2.生产产品对象;
3.使用对象方法。
代码:
工厂类 Factory.h
// // Created by Halo on 2019/10/14. // #ifndef FACTORY_FACTORY_H #define FACTORY_FACTORY_H #include "Product.h" //抽象手机工厂类 class Factory { public: //生产手机 virtual Phone* CreatePhone() = 0; }; //OPPO手机工厂 class OPPOFactory : public Factory { public: //OPPO手机工厂类 use a OPPO手机类 Phone* CreatePhone() override { return new OPPO(); } }; //VIVO手机工厂 class VIVOFactory : public Factory { public: Phone* CreatePhone() override { return new VIVO(); } }; //HUAWEI手机工厂 class HUAWEIFactory : public Factory { public: Phone* CreatePhone() override { return new HUAWEI(); } }; //XIAOMI手机工厂 class XIAOMIFactory : public Factory { public: Phone* CreatePhone() override { return new XIAOMI(); } }; #endif //FACTORY_FACTORY_H
产品类 Product.h
// // Created by Halo on 2019/10/14. // #ifndef FACTORY_PRODUCT_H #define FACTORY_PRODUCT_H #include <string> //抽象手机类 class Phone { public: //Phone() = default;; //得到手机名称 virtual std::string Say() = 0; //~Phone() = default; }; //具体手机类:OPPO class OPPO : public Phone { public: //OPPO() = default; std::string Say() override { return "OPPO 音乐手机!"; } //~OPPO() = default; }; //具体手机类:VIVO class VIVO : public Phone { public: //VIVO() = default; std::string Say() override { return "VIVO 照相手机!"; } //~VIVO() = default; }; //具体手机类:HUAWEI class HUAWEI : public Phone { public: //HUAWEI() = default; std::string Say() override { return "HUAWEI 商务手机!"; } //~HUAWEI() = default; }; //具体手机类:XIAOMI class XIAOMI : public Phone { public: //XIAOMI() = default; std::string Say() override { return "XIAOMI 性价比手机!"; } //~XIAOMI() = default; }; #endif //FACTORY_PRODUCT_H
用户 main.cpp
#include <iostream> #include "Factory.h" using namespace std; int main() { //创建OPPO手机工厂 Factory* f1 = new OPPOFactory(); //OPPO手机工厂制造手机 Phone* p1 = f1->CreatePhone(); //OPPO手机口号 cout << p1->Say() << endl; Factory* f2 = new VIVOFactory(); Phone* p2 = f2->CreatePhone(); cout << p2->Say() << endl; Factory* f3 = new HUAWEIFactory(); Phone* p3 = f3->CreatePhone(); cout << p3->Say() << endl; Factory* f4 = new XIAOMIFactory(); Phone* p4 = f4->CreatePhone(); cout << p4->Say() << endl; return 0; }