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的博客 1129

库存管理基于Excel的多商品组合订单需求拆解模型:SKU级供需预测与四情景压力测试系统设计 Excel 多商品组合订单的需求拆解|Excel模型与模拟数据

内容概要:本文档围绕Excel中多商品组合订单的基础SKU需求拆解,构建从订单行、组合用量表到仓库周需求、期初可供、计划到货及欠交结转的完整计算链条。通过四种组合、六种SKU、两座仓库和八个业务周的模拟数据,演示如何将组合套数准确转换为SKU件数,防止重复扣减与错误状态纳入,并按周递推供需覆盖与欠交变化。文档提供结构化输入校验、公式体系、守恒检查与四情景复算机制,确保结果可追溯、可核对。全部数据为基于固定随机种子生成的原创模拟记录,配套可编辑Excel工作簿与独立Python程序实现双向验证。 适合人群:适用于负责订单汇总、组合商品管理、库存分析、仓配协同、需求计划及业务分析文档编制的相关人员。日常使用者需掌握Excel基本操作如单元格引用、筛选与求和;具备Python基础者可配合标准库运行程序进行批量验证或数据重生成。业务管理岗可重点阅读结果与风险章节,结合工作表索引追踪数值来源。 使用场景及目标:适用于活动套单、同单含组合与单品、多仓备货、到货周期偏移及需求波动等场景。目标是实现组合订单向基础SKU的精准拆解,按周粒度完成供需匹配与欠交递推,识别输入冲突与窗口外到货影响,支持需求增幅、到货延期等多情景模拟分析,所有结论均可从源订单、BOM、Excel公式或独立程序追溯验证。 其他说明:项目交付包含A4文档、可编辑Excel、完整Python代码、CSV输入表、计算快照、四情景结果、测试记录、README指引及作者验收记录。采用固定随机种子确保数据一致性,强调输入有效性校验与双守恒(供给与需求)原则。Excel工作簿采用三层结构(源输入—公式计算—结果展示),支持手动编辑与自动重算,但扩容需重新生成网格。独立Python程序可用于交叉验证,保障模型可靠性。

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的博客 109

1705028(1).PDF

1705028(1).PDF

东汉AD35年世界历史地图矢量文件SHP格式.zip

本资源为《东汉AD35年世界历史地图矢量文件SHP格式》压缩包,文件大小约 29.99 MB,便于集中下载、整理和使用。具体内容请结合压缩包内的实际文件与说明查看。 在当前可读取的目录中,可见JSON 文件、属性表(.dbf)、投影说明文件(.prj)、Shapefile 主文件(.shp)、Shapefile 索引(.shx)。建议解压后保持原有目录结构,先浏览文件清单与说明,再选择需要的资料进行加载或整理。 应用方面,可根据实际资料用于学习练习、资料检索、研究整理或项目参考。使用时可先确定所需内容,建立清晰的文件分类,再按项目要求进行筛选、转换与汇总。 使用 Shapefile 数据时,请把实际配套的 .shp、.shx、.dbf 等文件保存在同一目录,并保持同名关联;加载后再检查坐标系与中文字段显示。如需叠加其它数据,请先统一坐标与字段口径。 数据来源、时间范围、坐标系、字段定义、精度和使用条件,请以实际文件及原始说明为准。本介绍不对文件名之外尚未核实的信息作额外承诺。

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

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

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

基于FastAPI Vue3 TypeScript的企业级全栈底座:类型共享、权限完整,三端同源 一套代码交付Web/H5/小程序,AI代码生成 RBAC Docker开箱即用一套开源的快速开发平台

基于FastAPI Vue3 TypeScript的企业级全栈底座:类型共享、权限完整,三端同源。一套完全开源的快速开发平台,提供免费使用。它结合了现代、高性能的技术栈,后端采用Fastapi + SQLAlchemy,前端采用基于 vue3 + typescript + vite + pinia + Element-Plus。

销售述职体系建设方案(含流程与评分表).docx

销售述职体系建设方案(含流程与评分表)

YOLO26算法室内办公环境二维码目标检测+训练好的模型+199张数据集+pyqt可视化界面.zip

附训练好的 YOLO 权重与 PyQt 可视化检测界面,页面底部含可视化效果预览,毕设/课设开箱即用。 【数据集概况】 · 检测类别(中文):[二维码(QRCode)] · 总计:199 张 · 测试集:20 张 · 验证集:40 张 · 训练集:139 张 【训练曲线与评估图】 【模型训练配置】 参数 | 值 模型 | yolo26n 训练轮数 | 100 epochs 输入尺寸 | 640x640 批次大小 | 24 优化器 | auto 初始学习率 | 0.01 训练设备 【关键指标汇总】 训练了 56 个 epoch,最终轮指标: 指标 | 数值 mAP50 | **0.9921** mAP50-95 | 0.8216 Precision | 0.9731 Recall | 1.0000 train/box_loss | 0.6220 train/cls_loss | 0.6579 val/box_loss | 0.7042 val/cls_loss | 0.7743 【训练过程分析】 从整体上看,模型在训练过程中表现稳定,尽管在某些阶段出现了轻微的波折,但总体上遵循了预设的收敛路径。前几轮中,loss 的急剧下降让人感觉仿佛是在玩“过山车”,尤其是在训练的前 10 轮,loss 从初始值 2.0 逐渐降到 1.0 以下,这表明模型在快速学习数据的基本特征。然而,从第 15 轮开始,loss 值并没有进一步明显下降,而是趋于平稳,这表明模型已经初步收敛。 在训练曲线的中期,从第 20 轮到第 35 轮,loss 并没有出现大幅波动或平台期。这个阶段的曲线相对平滑,loss 值基本维持在 0.6 至 0.7 之间,这表明模型的泛化能力在逐渐提升。尽管如此,这个阶段确实出现了一些细微的震荡,特别是在第... 使用场景:毕业设计、课程设计、深度学习入门、工业场景落地验证。

东汉AD185年世界历史地图矢量文件SHP格式.zip

本资源为《东汉AD185年世界历史地图矢量文件SHP格式》压缩包,文件大小约 28.48 MB,便于集中下载、整理和使用。具体内容请结合压缩包内的实际文件与说明查看。 在当前可读取的目录中,可见属性表(.dbf)、投影说明文件(.prj)、Shapefile 主文件(.shp)、Shapefile 索引(.shx)。建议解压后保持原有目录结构,先浏览文件清单与说明,再选择需要的资料进行加载或整理。 应用方面,可根据实际资料用于学习练习、资料检索、研究整理或项目参考。使用时可先确定所需内容,建立清晰的文件分类,再按项目要求进行筛选、转换与汇总。 使用 Shapefile 数据时,请把实际配套的 .shp、.shx、.dbf 等文件保存在同一目录,并保持同名关联;加载后再检查坐标系与中文字段显示。如需叠加其它数据,请先统一坐标与字段口径。 数据来源、时间范围、坐标系、字段定义、精度和使用条件,请以实际文件及原始说明为准。本介绍不对文件名之外尚未核实的信息作额外承诺。

老板演讲紧张怎么办之脱敏训练法.pdf

老板演讲紧张怎么办之脱敏训练法

东汉AD155年世界历史地图矢量文件SHP格式.zip

本资源为《东汉AD155年世界历史地图矢量文件SHP格式》压缩包,文件大小约 28.37 MB,便于集中下载、整理和使用。具体内容请结合压缩包内的实际文件与说明查看。 在当前可读取的目录中,可见属性表(.dbf)、投影说明文件(.prj)、Shapefile 主文件(.shp)、Shapefile 索引(.shx)。建议解压后保持原有目录结构,先浏览文件清单与说明,再选择需要的资料进行加载或整理。 应用方面,可根据实际资料用于学习练习、资料检索、研究整理或项目参考。使用时可先确定所需内容,建立清晰的文件分类,再按项目要求进行筛选、转换与汇总。 使用 Shapefile 数据时,请把实际配套的 .shp、.shx、.dbf 等文件保存在同一目录,并保持同名关联;加载后再检查坐标系与中文字段显示。如需叠加其它数据,请先统一坐标与字段口径。 数据来源、时间范围、坐标系、字段定义、精度和使用条件,请以实际文件及原始说明为准。本介绍不对文件名之外尚未核实的信息作额外承诺。

汽车专用零部件项目申报材料清单.docx

汽车专用零部件项目申报材料清单

AI第三篇:ScaBench-用真实审计竞赛数据构建可复现的 AI 审计评测集

AI第三篇:ScaBench-用真实审计竞赛数据构建可复现的 AI 审计评测集

演讲脱敏训练怎么坚持.pdf

演讲脱敏训练怎么坚持

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

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址