注:图片来源于 https://www.cnblogs.com/-saligia-/p/10216752.html
抽象工厂UML图解析:
抽象工厂模式:client用户需要三步:
1.创建工厂(一种工厂可以有多种功能);
2.生产产品对象;
3.使用对象方法。
代码:
Factory.h
// // Created by DELL on 2019/10/15. // #ifndef ABSTRACT_FACTORY_FACTORY_H #define ABSTRACT_FACTORY_FACTORY_H #include "Product.h" //工厂类,可以生产两种以上产品:Phone与PC class Factory { public: virtual Phone* CreatePhone() = 0; virtual PC* CreatePC() = 0; }; //HUAWEI工厂 class HUAWEI : public Factory { public: Phone* CreatePhone() override { return new HUAWEIPhone(); } PC* CreatePC() override { return new HUAWEIPC(); } }; //XIAOMI工厂 class XIAOMI : public Factory { public: Phone* CreatePhone() override { return new XIAOMIPhone(); } PC* CreatePC() override { return new XIAOMIPC(); } }; #endif //ABSTRACT_FACTORY_FACTORY_H
Product.h
// // Created by DELL on 2019/10/15. // #ifndef ABSTRACT_FACTORY_PRODUCT_H #define ABSTRACT_FACTORY_PRODUCT_H #include <string> //虚拟手机类 class Phone { public: virtual std::string Say() = 0; }; //虚拟笔记本电脑类 class PC { public: virtual std::string Say() = 0; }; //HUAWEI手机 class HUAWEIPhone : public Phone { public: std::string Say() override { return "HUAWEI phone, use HM OS"; } }; //XIAOMI手机 class XIAOMIPhone : public Phone { public: std::string Say() override { return "XIAOMI phone, use MIUI OS"; } }; //HUAWEI笔记本 class HUAWEIPC : public PC { public: std::string Say() override { return "HUAWEI PC, can use HM OS"; } }; //XIAOMI笔记本 class XIAOMIPC : public PC { std::string Say() override { return "XIAOMI PC, only can use Windows"; } }; #endif //ABSTRACT_FACTORY_PRODUCT_H
用户 main.cpp
#include <iostream> #include "Factory.h" using namespace std; int main() { //创建HUAWEI工厂 Factory* f1 = new HUAWEI(); Phone* phone1 = f1->CreatePhone(); cout << phone1->Say() << endl; PC* pc1 = f1->CreatePC(); cout << pc1->Say() << endl; //创建小米工厂 Factory* f2 = new XIAOMI(); Phone* phone2 = f2->CreatePhone(); cout << phone2->Say() << endl; PC* pc2 = f2->CreatePC(); cout << pc2->Say() << endl; return 0; }