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

相关文章

C# 比较两个list 之间元素差异的常用方法

《C#比较两个list之间元素差异的常用方法》:本文主要介绍C#比较两个list之间元素差异,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录1. 使用Except方法2. 使用Except的逆操作3. 使用LINQ的Join,GroupJoin

Python实现对阿里云OSS对象存储的操作详解

《Python实现对阿里云OSS对象存储的操作详解》这篇文章主要为大家详细介绍了Python实现对阿里云OSS对象存储的操作相关知识,包括连接,上传,下载,列举等功能,感兴趣的小伙伴可以了解下... 目录一、直接使用代码二、详细使用1. 环境准备2. 初始化配置3. bucket配置创建4. 文件上传到os

MySQL查询JSON数组字段包含特定字符串的方法

《MySQL查询JSON数组字段包含特定字符串的方法》在MySQL数据库中,当某个字段存储的是JSON数组,需要查询数组中包含特定字符串的记录时传统的LIKE语句无法直接使用,下面小编就为大家介绍两种... 目录问题背景解决方案对比1. 精确匹配方案(推荐)2. 模糊匹配方案参数化查询示例使用场景建议性能优

关于集合与数组转换实现方法

《关于集合与数组转换实现方法》:本文主要介绍关于集合与数组转换实现方法,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1、Arrays.asList()1.1、方法作用1.2、内部实现1.3、修改元素的影响1.4、注意事项2、list.toArray()2.1、方

使用Python实现可恢复式多线程下载器

《使用Python实现可恢复式多线程下载器》在数字时代,大文件下载已成为日常操作,本文将手把手教你用Python打造专业级下载器,实现断点续传,多线程加速,速度限制等功能,感兴趣的小伙伴可以了解下... 目录一、智能续传:从崩溃边缘抢救进度二、多线程加速:榨干网络带宽三、速度控制:做网络的好邻居四、终端交互

Python中注释使用方法举例详解

《Python中注释使用方法举例详解》在Python编程语言中注释是必不可少的一部分,它有助于提高代码的可读性和维护性,:本文主要介绍Python中注释使用方法的相关资料,需要的朋友可以参考下... 目录一、前言二、什么是注释?示例:三、单行注释语法:以 China编程# 开头,后面的内容为注释内容示例:示例:四

从入门到精通C++11 <chrono> 库特性

《从入门到精通C++11<chrono>库特性》chrono库是C++11中一个非常强大和实用的库,它为时间处理提供了丰富的功能和类型安全的接口,通过本文的介绍,我们了解了chrono库的基本概念... 目录一、引言1.1 为什么需要<chrono>库1.2<chrono>库的基本概念二、时间段(Durat

java实现docker镜像上传到harbor仓库的方式

《java实现docker镜像上传到harbor仓库的方式》:本文主要介绍java实现docker镜像上传到harbor仓库的方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录1. 前 言2. 编写工具类2.1 引入依赖包2.2 使用当前服务器的docker环境推送镜像2.2

C++20管道运算符的实现示例

《C++20管道运算符的实现示例》本文简要介绍C++20管道运算符的使用与实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录标准库的管道运算符使用自己实现类似的管道运算符我们不打算介绍太多,因为它实际属于c++20最为重要的

一文详解Git中分支本地和远程删除的方法

《一文详解Git中分支本地和远程删除的方法》在使用Git进行版本控制的过程中,我们会创建多个分支来进行不同功能的开发,这就容易涉及到如何正确地删除本地分支和远程分支,下面我们就来看看相关的实现方法吧... 目录技术背景实现步骤删除本地分支删除远程www.chinasem.cn分支同步删除信息到其他机器示例步骤