Understanding and Implementing Factory Pattern in C++

有限单元法(The Finite Element Method) 简介 有限元法最初的概念源自用结构力学的方法解决弹性力学的问题,后来扩展到各种用微分方程描述的学科。最初的有限单元法多用于工程计算,随着计算机性能的不断增强以及对图形表现真实性的进一步需求,有限单元法也逐渐应用到了图形的领域。连续介质力学 Continuum Mechanics 在图形学中,可变形的物体通常建模为连续介质的三维物体,其中最重要的三个量是... 阅读详情

Introduction

This article aims at understanding the Factory Pattern and a basic implementation of Factory pattern in C++.

Background

There are many scenarios when a class needs to create several objects. The class can do so freely but it has to know about each and every class. There is a possibility that the class can't anticipate all the objects it needs to create. The second scenario could be that the class wants to delegate the responsibility of creating the objects to its subclasses or perhaps some helper functions.

If we have any of the above mentioned scenarios, we can have the Factory pattern. The idea of the factory pattern is to have the classes ability to create other classes without them knowing about all the possible classes that exists. This gives us extensibility. With factory pattern, we get the possibility of creating, maintaining and manipulating a collection of different objects that have some common characteristics. The main use of this pattern is in classes that manage a lot of objects like Document Manager, Control manager, Facility Manager.

GOF defines factory pattern as "Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory pattern lets a class defer instantiation to subclasses".

Using the Code

Let us now look at the UML diagram borrowed straight from GOFs book:

factory pattern

Let us try to see what each of these classes represents:

  • Product: defines the interface of objects the factory pattern creates
  • ConcreteProduct: implements the Product interface
  • Creator: declares the factory method, which returns an object of typeProduct
  • ConcreteCreator: overrides the factory method to return an instance of aConcreteProduct

Now what we have tried to do in our small exercise is that we have created a system that will manage the receivable for different type of employees, i.e.,Manager, Engineer etc. so let's go ahead and look at our implementation of the factory pattern.

Creating the Abstract Product

First of all, we need to define an abstract class that will define the common interface to different type of items available to the employees. These items could be physical receivables likeCars, CellPhones or virtual receivables like insurance.

class AItems
{
    std::string name;
public:
    AItems(std::string n)
        :name(n)
    {

    }

    //This method is for testing only
    std::string GetName()
    {
        return name;
    }
};


What we have done here is that we have created the abstract Product class that we saw in the diagram. So if we map our implementation now with the GOFs diagram, we have the following classes ready:

factory pattern 1

Creating the Concrete Products

Now we need to create the real Items (receivables) that the employees can get. We have the interface for the receivables ready so what we need to do now is to use this interface to create the Items that the company offers to its employees.

//Lets declare all the concrete ITEMS
class Car : public AItems
{
public: Car()
        :AItems("Car"){}
};

class CellPhone :public  AItems
{
public: CellPhone()
        :AItems("CellPhone"){}
};

class Computer : public AItems
{
public: Computer()
        :AItems("Computer"){}
};

class LapTop : public AItems
{
public: LapTop()
        :AItems("LapTop"){}
};

class MotorBike : public AItems
{
public: MotorBike()
        :AItems("MotorBike"){}
};

class EntertainmentAllowance : public AItems
{
public: EntertainmentAllowance()
        :AItems("EntertainmentAllowance"){}
};

class TravelAllowance : public AItems
{
public: TravelAllowance()
        :AItems("TravelAllowance"){}
};
class Salary : public AItems
{
public: Salary()
        :AItems("Salary"){}
};

class Incentives : public AItems
{
public: Incentives()
        :AItems("Incentives"){}
};


What we have done here is that we have created the ConcreteProduct class that we saw in the diagram. So if we map our implementation now with the GOFs diagram:

factory pattern 2

Creating the Abstract Creator

Now we need the abstract class that will have the functionality common to all theEmployees. All the employees are entitled to get some items so this class will provide the functionality to add or remove the items for the particular type ofemployee.

//Header File
class AEmployee
{
public:
    std::vector<AItems> benefits;
    enum EMP_TYPE
    {
        ENGINEER,
        MANAGER
    };

    void CreateAndAddBenefit(AItems ben);

    void PrintBenefits();

    static AEmployee* CreateEmployee(EMP_TYPE empType);
};

//CPP File
AEmployee* AEmployee::CreateEmployee(EMP_TYPE empType)
{
    if(empType == EMP_TYPE::ENGINEER)
    {
        return new Engineer();
    }
    else if(empType == EMP_TYPE::MANAGER)
    {
        return new Manager();
    }
}

void AEmployee::CreateAndAddBenefit(AItems ben)
{
    benefits.push_back(ben);
}

void AEmployee::PrintBenefits()
{
    for(std::vector<AItems>::iterator iter = benefits.begin(); 
        iter != benefits.end(); ++iter)
    {
        std::cout << (*iter).GetName() << "\n";
    }
}


What we have done here is that we have created the Creator class that we saw in the diagram. So if we map our implementation now with the GOFs diagram:

factory pattern 3

Creating the Concrete Creators

Now we need the specialization of AEmployee class. These classes will represent the type ofemployees that could exist in the organization.

//Header File
class Manager : public AEmployee
{
public:
    Manager(void);
    
};

class Engineer : public AEmployee
{
public:
    Engineer(void);
};

//CPP File
Manager::Manager(void)    
{    
    CreateAndAddBenefit(Car());
    CreateAndAddBenefit(CellPhone());
    CreateAndAddBenefit(LapTop());
    CreateAndAddBenefit(EntertainmentAllowance());
    CreateAndAddBenefit(TravelAllowance());
    CreateAndAddBenefit(Salary());
    CreateAndAddBenefit(Incentives());
}

Engineer::Engineer(void)
{
    CreateAndAddBenefit(Computer());
    CreateAndAddBenefit(MotorBike());
    CreateAndAddBenefit(TravelAllowance());
    CreateAndAddBenefit(Salary());
}


Finally, what we did is to create the ConcreteCreator class that we saw in the diagram. So let's map our implementation now with the GOFs one last time:

factory pattern 4

Testing the Application

Now let's test the application and see how we can create the various employees and see the receivables they are entitled for.

int main(int argc, char* argv[])
{
    AEmployee *emp = AEmployee::CreateEmployee(AEmployee::EMP_TYPE::MANAGER);
    cout << "Recievables for Manager:\n";
    emp->PrintBenefits();

    getchar();
    delete emp;

    emp = AEmployee::CreateEmployee(AEmployee::EMP_TYPE::ENGINEER);
    cout << "Recievables for Engineer:\n";
    emp->PrintBenefits();

    getchar();
    delete emp;
    return 0;
}


Points of Interest

The major benefit of using the factory pattern is that there is no need for the client code to know the application specific classes. There could be more than a 100 type ofItems in our particular example and the client code still doesn't have to know about any one of them. The client code can simply use the factory to create and use the appropriate type.

This article covers the basics of Factory Pattern and provides a basic implementation in C++. I have a similar implementation for the same pattern in C# too. Let's now just try to find its applicability.

Use the Factory pattern when:

  • A class can't anticipate the class of objects it must create.
  • A class wants its subclasses to specify the objects it creates.
  • Classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate.
Understanding MPEG4 Understanding MPEG4 ,MPEG4,原始白皮书,绝对有用,与大家分享。 立即下载

相关推荐

<Understanding and Implementing the Finite Element Methods-理解与实现有限元> 源代码

包括Lagrange三角形单元,等参数单元,以及针对椭圆方程的几种自适应方法的Matlab源程序。

matlab有限元分析实例,有限元分析与应用 | Finite Element Method (FEM) Analysis and Applications...

Do you want to become an expert at structural analysis?Finite Element Method (FEM) is a powerful tool. FEM is an effective numerical technique for partial differential equations (PDEs) in engineering....

weixin_29545089的博客 1128

VLOOKUP_fixed.py

VLOOKUP_fixed.py

大型CAx(CAD/CAE/CAPP/CAM)工业软件开发中的关键组件

通过对FreeCAD、SALOME等多款代码的分析研究,发现这些软件在架构设计、模块实现等方面,存在许多相似(同)的技术思想。因此,有必要对这些共性、主流的技术予以总结分析。

国产CAx(CAD/CAE/CAM)软件研发 1万+

D打卡签到,蓝牙中继,广播信号模拟器

模拟WIFI或蓝牙,有如下4种运行模式 1、WIFI模式:指定SSID、BSSID名称等,模拟WIFI,供设备连接。 2、蓝牙静态模式:指定MAC地址,广播固定的RAW数据。 3、蓝牙动态主机模式:扫描周围蓝牙设备,获取指定MAC地址的蓝牙及其RAW数据,实时发送至Cloud云端,可以设定时间段,只在设定的时间段内发送。 4、蓝牙动态从机模式:指定MAC地址,从Cloud云端获取动态主机模式实时上传的该MAC地址的RAW数据,并广播RAW数据。 准备工作: 1、板子:选择ESP32C3或ESP32C3 Supermini 2、nRF Connect手机app:用于扫描获取待模拟蓝牙设备的MAC和RAW数据。 Wifi分析仪或WiFi魔盒手机APP:用于扫描获取待模拟WIFI设备的SSID和BSSID。 3、可使用官方flash_download_tool_3.9.11工具来固件烧录。 使用说明: 上述完成后,设备首次上电,RESET一侧的指示灯会常亮,可以把它理解成电源指示灯; BOOT一侧的灯会亮,该灯常亮,表示设备开启了AP模式,此时设备会发射一个WIFI信号源,名称为ESPWIFI_AP,密码为12345678,手机或电脑连接该WIFI,浏览器输入192.168.4.1,进入设备的配置页面,进行相应的配置,其中动态主机模式和动态从机模式的SSID、Pwd 及要模拟的蓝牙MAC地址。配置完成并保存后,会重启,重启后设备会按照保存的配置运行。若下次要修改设备配置,可以长按BOOT按键,等待BOOT一侧的灯常亮,即进入AP模式,再按照上述流程配置即可。 仅用于蓝牙设备的开发与调试,请勿用于签到等违法违纪用途。

YOLO26算法心电图十二导联目标检测+训练好的模型+368张数据集+pyqt可视化界面.zip

附训练好的 YOLO 权重与 PyQt 可视化检测界面,页面底部含可视化效果预览,毕设/课设开箱即用。 【数据集概况】 · 检测类别(中文):[导联I(I), 导联II(II), 导联III(III), 胸导联V1(V1), 胸导联V2(V2), 胸导联V3(V3), 胸导联V4(V4), 胸导联V5(V5), 胸导联V6(V6), 加压肢体导联aVF(aVF), 加压肢体导联aVL(aVL), 加压肢体导联aVR(aVR)] · 训练集:313 张 · 验证集:37 张 · 测试集:18 张 · 总计:368 张 该数据集聚焦于临床心电图信号的精准识别与定位,其核心检测目标为标准12导联心电图中的各个独立导联波形区域,涵盖肢体导联(I、II、III)与加压肢体导联(aVR、aVL、aVF),以及胸前导联(V1至V6),适用于心电图自动分析系统中对各导联位置的快速准确标注与分类。数据采集场景真实还原了医院心电图室或急诊监护环境下的标准心电图记录纸,波形清晰、基线稳定,具有高度临床参考价值。... 【训练曲线与评估图】 【模型训练配置】 参数 | 值 模型 | yolo26n 训练轮数 | 100 epochs 输入尺寸 | 640x640 批次大小 | 24 优化器 | auto 初始学习率 | 0.01 训练设备 【关键指标汇总】 训练了 57 个 epoch,最终轮指标: 指标 | 数值 mAP50 | **0.9708** mAP50-95 | 0.6344 Precision | 0.8990 Recall | 0.9191 train/box_loss | 1.2231 train/cls_loss | 0.9703 val/box_loss | 1.2779 val/cls_loss | 0.... 使用场景:毕业设计、课程设计、深度学习入门、工业场景落地验证。

Understanding the WPF Layout System

Many people don't understand how the WPF layout system works, or how that knowledge can help them in their projects. I intend to shine a little light on the mechanics behind all those cool layout cont...

weixin_34013044的博客 108

企业级AI助手平台 开箱即用的全栈AI平台,支持多智能体协同、Supervisor模式编排、多种决策模式、RAG技术和流程编排能力 支持多厂商大模型统一接入与管理,安全可控的企业知识库与高精度检索优化

企业级AI应用开发框架,支持多厂商大模型统一接入与管理,安全可控的企业知识库与高精度检索优化能力,提供可视化流程编排、自主决策智能体与多智能体协同调度,兼容主流 Agent Skill 协议,帮助企业与开发者零门槛快速构建安全、高效、可落地的AI智能体应用与行业解决方案。

2024 《计算机网络》实验教学指导书.doc

2024 《计算机网络》实验教学指导书.doc

Java低代码, 轻量级, 支持国产化 国密 AI大模型MCP服务 商业免费 包括核心模块如:组织机构、角色用户、权限授权、数据权限、内容管理、工作流、Spring Cloud 微服务、AI大模型等

Java低代码, 轻量级, 支持国产化 国密 AI大模型MCP服务 商业免费 Spring Boot, MyBatis, Flowable, TypeScript, Vue, Antdv, 包括核心模块如:组织机构、角色用户、权限授权、数据权限、内容管理、工作流、Spring Cloud 微服务、AI大模型、代码生成器等

文创媒体电商行业智算中心(AIDC)建设规划方案.pptx

文创媒体电商行业智算中心(AIDC)建设规划方案.pptx

基于MPC的风储联合调频模型研究(Simulink仿真实现)

内容概要:本文系统研究了基于模型预测控制(MPC)的风能与储能系统联合频率调节模型,并通过Simulink工具实现了完整的仿真验证。文章深入剖析了风储联合系统的整体架构设计,详细阐述了MPC控制器的建模原理及其在电网频率调节中的具体应用机制,重点探讨了系统在应对负荷突变与风电功率波动等典型扰动下的动态响应特性与控制性能表现。通过与传统控制策略的仿真实验对比,充分验证了所提出的MPC方法在提升电网频率稳定性、抑制频率偏差方面的显著优越性,并进一步分析了控制器关键参数对系统整体性能的影响规律,为高性能控制策略的设计提供了理论依据。; 适合人群:具备电力系统分析、自动控制理论基础,熟练掌握Simulink/Matlab仿真环境,从事新能源并网、电力系统稳定控制、储能系统集成与优化等相关领域的研究生、科研人员及工程技术人员。; 使用场景及目标:①应用于高比例可再生能源接入背景下电网频率调节的关键技术研究;②为风储联合系统的规划、设计与运行优化提供先进的控制策略参考;③作为模型预测控制在电力系统领域应用的经典教学案例,深化对MPC预测机制、滚动优化与反馈校正等核心原理的理解与实践能力。; 阅读建议:建议读者结合提供的Simulink仿真模型进行同步操作与验证,重点关注MPC控制器的状态空间建模、预测时域设定、代价函数构建及参数整定过程,通过对比不同工况与参数配置下的仿真结果,深入理解风储系统协同调频的作用机理与MPC控制的优势所在。

集团企业数字化转型AI智能体平台规划及场景应用方案.pptx

集团企业数字化转型AI智能体平台规划及场景应用方案.pptx

数据驱动复杂网络的数据驱动控制(Matlab代码实现)

内容概要:本文系统介绍了《【数据驱动】复杂网络的数据驱动控制(Matlab代码实现)》这一技术资源,聚焦于复杂网络系统中基于数据驱动的先进控制方法,依托Matlab平台实现建模、仿真与控制策略开发。内容深入涵盖数据驱动控制的核心原理、Koopman算子理论在非线性系统线性化中的应用、机器学习与动态系统建模的融合机制,以及如何在无需精确物理模型的前提下,利用观测数据构建高效控制器。资源提供了完整的Matlab代码实例,覆盖从数据采集、特征提取、模型辨识到控制器设计与性能评估的全流程,突出在电力系统、智能电网、工业自动化等典型复杂网络场景下的应用潜力与工程可行性。; 适合人群:具备一定Matlab编程能力与自动控制理论基础的研究生、科研人员及工程技术人员,尤其适用于从事数据驱动控制、复杂网络建模、智能优化与系统辨识等方向的高校师生和研发工作者。; 使用场景及目标:① 深入理解数据驱动控制在复杂网络中的理论基础与实现路径;② 借助配套Matlab代码快速搭建仿真环境,开展算法验证与性能对比;③ 应用于电力系统稳定性控制、可再生能源集成、工业过程监控等实际工程问题的研究与优化;④ 支撑高水平学术论文撰写、EI/SCI期刊成果复现与科研项目申报。; 阅读建议:建议读者结合文档中的理论推导与代码实现逐项调试运行,深入剖析Koopman算子、模型预测控制(MPC)等关键算法的实现细节;鼓励在现有代码基础上进行参数调整、模型拓展与创新性改进,强化理论与实践的深度融合,提升科研创新能力。

基于动态窗口法DWA的机器人路径规划研究(Matlab代码实现)

内容概要:本文系统研究了基于动态窗口法(DWA)的机器人局部路径规划算法,深入剖析其在动态环境中实现自主避障与实时轨迹优化的核心机制。文章详细阐述了DWA算法的速度空间采样策略、轨迹预测模型、动力学约束处理及多目标代价函数的设计原理,并通过构建完整的Matlab仿真框架验证算法有效性。结合典型场景的仿真实验,展示了机器人在复杂障碍物环境下如何实时生成安全、平滑且符合运动学约束的最优路径,充分体现了DWA在移动机器人导航中的实用性与鲁棒性。; 适合人群:具备机器人运动规划基础知识和Matlab编程能力,从事智能移动机器人、自动驾驶或服务机器人研发的研究生、科研人员及工程技术人员。; 使用场景及目标:①深入理解DWA算法的理论基础与实现细节;②掌握机器人局部路径规划的仿真实现方法;③为实际机器人系统的导航模块开发提供可复用的算法原型与代码参考;④作为进一步研究高级导航算法(如TEB、MPC)的技术基础。; 阅读建议:建议结合提供的Matlab代码逐模块分析与调试,重点关注速度采样、轨迹积分、障碍物距离计算及代价评估等关键环节,通过调整参数在不同地图环境中进行对比实验,以深刻把握算法性能与参数之间的关系,进而提升对实时路径规划系统设计的理解与应用能力。

【轴承故障诊断】用于轴承故障诊断的集中时频分析研究(Matlab代码实现)

内容概要:本文系统研究了用于轴承故障诊断的集中时频分析技术,重点解决了传统时频分析方法在处理非平稳信号时存在的能量分散与分辨率不足等问题。通过引入集中时频分析方法,能够有效聚焦信号能量,精确提取轴承故障特征频率,提升故障识别的准确性与时效性。文章详细阐述了该方法的理论基础,并结合仿真信号与实际实验数据验证其优越性能,同时提供了完整的Matlab代码实现流程,涵盖信号预处理、时频变换、参数优化及结果可视化等环节,便于读者复现与拓展应用。; 适合人群:具备一定信号处理理论基础和Matlab编程能力的研究生、科研人员,以及从事机械设备状态监测、故障诊断与预测性维护工作的工程技术人员。; 使用场景及目标:①应用于电机、风机、齿轮箱等旋转机械的早期轴承故障检测,实现故障预警;②提升工业设备运维系统的智能化水平,支撑预测性维护体系构建;③作为高校或研究机构在信号处理、机械故障诊断等课程中的教学案例与实践素材。; 阅读建议:建议读者结合文中提供的Matlab代码逐段运行与调试,深入理解集中时频分布的生成机制及其关键参数(如核函数选择、平滑窗口大小)对诊断效果的影响,并尝试将其应用于其他类型的机械故障信号分析中,开展对比研究以深化对该方法适用性的认识。

上一篇: Matlab常用操作。。
下一篇: 用javascript 验证两个输入框的开始时间和结束时间
xiaoding133
博客等级 码龄19年 415粉丝 159原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值