c++11工厂子类实现自注册的两种方法

2024-09-08 09:18

本文主要是介绍c++11工厂子类实现自注册的两种方法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

文章目录

    • 一、产品类构建
      • 1. 猫基类与各品种猫子类
      • 2.狗基类与各品种狗子类
    • 二、工厂类构建
    • 三、客户端使用switch-case实现调用不同工厂子类
    • 四、自注册方法一:公开注册函数显式注册
    • 五、自注册方法二:构造函数隐形注册
    • 总结

一、产品类构建

1. 猫基类与各品种猫子类

class Cat {
public:virtual void Printer() = 0;
};class Persian : public Cat {
public:virtual void Printer() {std::cout<<"I am a cat, persian."<<std::endl;}
};class Birman : public Cat {
public:virtual void Printer() {std::cout<<"I am a cat, Birman."<<std::endl;}
};class NorwegianForestCat : public Cat {
public:virtual void Printer() {std::cout<<"I am a Norwegian Forest Cat."<<std::endl;}
};class Ragdoll : public Cat {
public:virtual void Printer() {std::cout<<"I am a Cat, Ragdoll."<<std::endl;}
};class Himalayan : public Cat {
public:virtual void Printer() {std::cout<<"I am a Cat, Himalayan."<<std::endl;}
};

2.狗基类与各品种狗子类

class Dog {
public:virtual void Printer() = 0;
};class Affenpinscher : public Dog {
public:virtual void Printer() {std::cout<<"I am a Dog, Affenpinscher"<<std::endl;;}
};class AfghanHound  : public Dog {
public:virtual void Printer() {std::cout<<"I am a Dog, Afghan Hound "<<std::endl;;}
};class AiredaleTerrier  : public Dog {
public:virtual void Printer() {std::cout<<"I am a Dog, Airedale Terrier "<<std::endl;;}
};class Akita  : public Dog {
public:virtual void Printer() {std::cout<<"I am a Dog, Akita "<<std::endl;;}
};class AlaskanMalamute  : public Dog {
public:virtual void Printer() {std::cout<<"I am a Dog, Alaskan Malamute "<<std::endl;;}
};

二、工厂类构建

现在假设有五家动物繁育工厂,Animal1Factory,Animal2Factory,Animal3Factory,Animal4Factory,Animal5Factory。

  • Animal1Factoryt负责繁育的品种猫与狗分别为:Persian与Affenpinscher;
  • Animal2Factory负责繁育的品种猫与狗分别为:Birman与AfghanHound;
  • Animal3Factory负责繁育的品种猫与狗分别为:NorwegianForestCat与AiredaleTerrier;
  • Animal4Factory负责繁育的品种猫与狗分别为:Ragdoll与Akita;
  • Animal5Factory负责繁育的品种猫与狗分别为:Himalayan与AlaskanMalamute。

可构建动物繁育工厂基类:

class AnimalFactory {
public:virtual Cat *produceCat() = 0;virtual Dog *produceDog() = 0;
}; 

其他五个动物繁育工厂子类构建如下:

class Animal1Factory : public AnimalFactory{
public:Cat *produceCat(){return new Persian();}Dog *produceDog(){return new Affenpinscher();}
}; class Animal2Factory : public AnimalFactory{
public:Cat *produceCat(){return new Birman();}Dog *produceDog(){return new AfghanHound();}   
};class Animal3Factory : public AnimalFactory{
public:Cat *produceCat(){return new Ragdoll();}Dog *produceDog(){return new AiredaleTerrier();}   
};class Animal4Factory : public AnimalFactory{
public:Cat *produceCat(){return new NorwegianForestCat();}Dog *produceDog(){return new Akita();}   
};
class Animal5Factory : public AnimalFactory{
public:Cat *produceCat(){return new Himalayan();}Dog *produceDog(){return new AlaskanMalamute();}   
};

三、客户端使用switch-case实现调用不同工厂子类

对以上构建的各产品类与工厂类,可在客户端使用switch-case根据不同的key去创建不同的派生工厂类对象,实现产生该工厂繁育的品种猫与狗。

int main(int argc, char **argv)
{for (size_t i = 0; i < 100; i++){AnimalFactory* factory = 0;int factory_name;std::cout<<"please input the factory index: ";std::cin>>factory_name;switch (factory_name) {case 1:factory = new Animal1Factory();break;case 2:factory = new Animal2Factory();break;case 3:factory = new Animal3Factory();break;case 4:factory = new Animal4Factory();break;case 5:factory = new Animal5Factory();break;default:break;}if (factory != 0){Cat* cat = factory->produceCat();Dog* dog = factory->produceDog();cat->Printer();dog->Printer();}        }return 0;
}

输出如下:
在这里插入图片描述

如果工厂子类个数已经确定,个数也不多的时候,用switch-case来调用工厂子类没啥问题。但是,随着工厂子类数越来越多,这个switch-case结构就显得有点傻了。例如,一个具有将近100多个工厂子类库,维护这样一个switch-case简直是肉疼。并且,switch-case调用工厂子类方式对于需要突然新增工厂子类的项目非常不友好。下面将要介绍的工厂子类自注册方法,便是解决该问题的一个很好的途径。

四、自注册方法一:公开注册函数显式注册

这是介绍的两种自注册方法之一,利用类内的公开注册函数显示注册工厂子类。另一种是在构造函数中隐式注册自己。我个人更加偏爱于后者。

自注册的方法,将各子类共用一个注册表,在构造完后与实例化前,将子类注册进全局的注册表。

  • 对工厂基类新增一些功能函数,用来注册新的工厂子类,并从注册表中获取某一子类:
class AnimalFactory {
public:virtual Cat *produceCat() = 0;virtual Dog *produceDog() = 0;static AnimalFactory* GetInstance(std::string name){_instance = LookUp(name);return _instance;}static void Register(const std::string name, AnimalFactory* func){AnimalFactory* regist = LookUp(name); // 防止重复注册,保证各子类的唯一性if (regist != NULL){return;}else{registry_.insert(std::make_pair(name, func));}}
protected: static AnimalFactory* LookUp(std::string name){std::map<std::string, AnimalFactory*>::iterator iter = registry_.find(name);if (iter != registry_.end())return iter->second;elsereturn NULL;        }
private:static std::map<std::string, AnimalFactory*> registry_; static AnimalFactory* _instance;
}; AnimalFactory* AnimalFactory::_instance = NULL;
std::map<std::string, AnimalFactory*> AnimalFactory::registry_;
  • 各工厂子类增加静态函数static void Regist() ,具体代码如下所示:
class Animal1Factory : public AnimalFactory{
public:Cat *produceCat(){return new Persian();}Dog *produceDog(){return new Affenpinscher();}static void Regist(){AnimalFactory::Register("Animal1Factory", new Animal1Factory());}   
}; class Animal2Factory : public AnimalFactory{
public:Cat *produceCat(){return new Birman();}Dog *produceDog(){return new AfghanHound();}static void Regist(){AnimalFactory::Register("Animal2Factory", new Animal2Factory());}   
};class Animal3Factory : public AnimalFactory{
public:Cat *produceCat(){return new Ragdoll();}Dog *produceDog(){return new AiredaleTerrier();}static void Regist(){AnimalFactory::Register("Animal3Factory", new Animal3Factory());}    
};class Animal4Factory : public AnimalFactory{
public:Cat *produceCat(){return new NorwegianForestCat();}Dog *produceDog(){return new Akita();}static void Regist(){AnimalFactory::Register("Animal4Factory", new Animal4Factory());}       
};class Animal5Factory : public AnimalFactory{
public:Cat *produceCat(){return new Himalayan();}Dog *produceDog(){return new AlaskanMalamute();}static void Regist(){AnimalFactory::Register("Animal5Factory", new Animal5Factory());}       
};
  • 客户端调用工厂子类如下:
static void before_main()
{std::cout<<"regist sub factory..."<<std::endl;Animal1Factory::Regist();Animal2Factory::Regist();Animal3Factory::Regist();Animal4Factory::Regist();Animal5Factory::Regist();
}int main(int argc, char **argv)
{before_main();for (size_t i = 0; i < 100; i++){AnimalFactory* factory = 0;std::string factory_name;std::cout<<"please input the factory name: ";std::cin>>factory_name;factory = AnimalFactory::GetInstance(factory_name);if (factory != 0){Cat* cat = factory->produceCat();Dog* dog = factory->produceDog();cat->Printer();dog->Printer();}        }return 0;
}

输出如下:
在这里插入图片描述

五、自注册方法二:构造函数隐形注册

上面介绍的自注册方法,需要在使用工厂子类前,在客户端对各子类进行一个显式可见的注册。这样做对于使用它们的客户仍不是很友好。现在介绍一种在构造函数内隐形注册的方法,此方法不需要用户在客户端对各工厂子类进行注册。

  • 工厂基类与第一种自注册方法一样

  • 各子类工厂的构造函数中添加Animal1Factory(){AnimalFactory::Register("Animal1Factory", this);},并在子类未尾添加该子类的一个静态实例,具体代码如下:

class Animal1Factory : public AnimalFactory{
public:Cat *produceCat(){return new Persian();}Dog *produceDog(){return new Affenpinscher();}Animal1Factory(){AnimalFactory::Register("Animal1Factory", this);}
}; 
static Animal1Factory animal1factory;class Animal2Factory : public AnimalFactory{
public:Cat *produceCat(){return new Birman();}Dog *produceDog(){return new AfghanHound();}Animal2Factory(){AnimalFactory::Register("Animal2Factory", this);}      
};
static Animal2Factory animal2factory; // 添加一个静态实例,实现该子类的注册class Animal3Factory : public AnimalFactory{
public:Cat *produceCat(){return new Ragdoll();}Dog *produceDog(){return new AiredaleTerrier();}Animal3Factory(){AnimalFactory::Register("Animal3Factory", this);}      
};
static Animal3Factory animal3factory;class Animal4Factory : public AnimalFactory{
public:Cat *produceCat(){return new NorwegianForestCat();}Dog *produceDog(){return new Akita();}Animal4Factory(){AnimalFactory::Register("Animal4Factory", this);}      
};
static Animal4Factory animal4factory;class Animal5Factory : public AnimalFactory{
public:Cat *produceCat(){return new Himalayan();}Dog *produceDog(){return new AlaskanMalamute();}Animal5Factory(){AnimalFactory::Register("Animal5Factory", this);}       
};
static Animal5Factory animal5factory;
  • 客户端调用工厂子类如下(注意,此时已经在客户端见不到注册的痕迹):
int main(int argc, char **argv)
{for (size_t i = 0; i < 100; i++){AnimalFactory* factory = 0;std::string factory_name;std::cout<<"please input the factory name: ";std::cin>>factory_name;factory = AnimalFactory::GetInstance(factory_name);if (factory != 0){Cat* cat = factory->produceCat();Dog* dog = factory->produceDog();cat->Printer();dog->Printer();}        }return 0;
}

输出:
在这里插入图片描述

总结

利用C++工厂方法,可以灵活的实现丰富的功能。正如工厂方法里的名词:工厂-产品,工厂负责生产产品。不同的工厂会产生同样类型的产品,就像衣服有很多种品牌(工厂),然后,衣服也粗分为裤子、外套等(产品)。在工厂-产品模式下,自注册其实分为两层:1)新产品越来越多,需要对新产品进行注册;2)新增加的品牌也会越来越多,需要对新工厂进行注册。网上对前一种注册应用介绍较多,因此,本文在工厂子类自注册应用背景下对自注册方法进行介绍。自注册避免了客户端调用冗长的switch-case,其中利用公开注册函数仍需要在正式使用子类前,对各子类进行注册,构造函数注册法则将注册隐藏在类文件中,当新工厂出现时,客户代码具有最好的兼容性。

这篇关于c++11工厂子类实现自注册的两种方法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1147707

相关文章

JavaScript中的reduce方法执行过程、使用场景及进阶用法

《JavaScript中的reduce方法执行过程、使用场景及进阶用法》:本文主要介绍JavaScript中的reduce方法执行过程、使用场景及进阶用法的相关资料,reduce是JavaScri... 目录1. 什么是reduce2. reduce语法2.1 语法2.2 参数说明3. reduce执行过程

C#中读取XML文件的四种常用方法

《C#中读取XML文件的四种常用方法》Xml是Internet环境中跨平台的,依赖于内容的技术,是当前处理结构化文档信息的有力工具,下面我们就来看看C#中读取XML文件的方法都有哪些吧... 目录XML简介格式C#读取XML文件方法使用XmlDocument使用XmlTextReader/XmlTextWr

如何使用Java实现请求deepseek

《如何使用Java实现请求deepseek》这篇文章主要为大家详细介绍了如何使用Java实现请求deepseek功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1.deepseek的api创建2.Java实现请求deepseek2.1 pom文件2.2 json转化文件2.2

python使用fastapi实现多语言国际化的操作指南

《python使用fastapi实现多语言国际化的操作指南》本文介绍了使用Python和FastAPI实现多语言国际化的操作指南,包括多语言架构技术栈、翻译管理、前端本地化、语言切换机制以及常见陷阱和... 目录多语言国际化实现指南项目多语言架构技术栈目录结构翻译工作流1. 翻译数据存储2. 翻译生成脚本

C++初始化数组的几种常见方法(简单易懂)

《C++初始化数组的几种常见方法(简单易懂)》本文介绍了C++中数组的初始化方法,包括一维数组和二维数组的初始化,以及用new动态初始化数组,在C++11及以上版本中,还提供了使用std::array... 目录1、初始化一维数组1.1、使用列表初始化(推荐方式)1.2、初始化部分列表1.3、使用std::

C++ Primer 多维数组的使用

《C++Primer多维数组的使用》本文主要介绍了多维数组在C++语言中的定义、初始化、下标引用以及使用范围for语句处理多维数组的方法,具有一定的参考价值,感兴趣的可以了解一下... 目录多维数组多维数组的初始化多维数组的下标引用使用范围for语句处理多维数组指针和多维数组多维数组严格来说,C++语言没

Springboot中分析SQL性能的两种方式详解

《Springboot中分析SQL性能的两种方式详解》文章介绍了SQL性能分析的两种方式:MyBatis-Plus性能分析插件和p6spy框架,MyBatis-Plus插件配置简单,适用于开发和测试环... 目录SQL性能分析的两种方式:功能介绍实现方式:实现步骤:SQL性能分析的两种方式:功能介绍记录

如何通过Python实现一个消息队列

《如何通过Python实现一个消息队列》这篇文章主要为大家详细介绍了如何通过Python实现一个简单的消息队列,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录如何通过 python 实现消息队列如何把 http 请求放在队列中执行1. 使用 queue.Queue 和 reque

Python如何实现PDF隐私信息检测

《Python如何实现PDF隐私信息检测》随着越来越多的个人信息以电子形式存储和传输,确保这些信息的安全至关重要,本文将介绍如何使用Python检测PDF文件中的隐私信息,需要的可以参考下... 目录项目背景技术栈代码解析功能说明运行结php果在当今,数据隐私保护变得尤为重要。随着越来越多的个人信息以电子形

使用 sql-research-assistant进行 SQL 数据库研究的实战指南(代码实现演示)

《使用sql-research-assistant进行SQL数据库研究的实战指南(代码实现演示)》本文介绍了sql-research-assistant工具,该工具基于LangChain框架,集... 目录技术背景介绍核心原理解析代码实现演示安装和配置项目集成LangSmith 配置(可选)启动服务应用场景