文章目录

  • 一、产品类构建
    • 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工厂子类实现自注册的两种方法相关推荐

  1. C++/C++11中用于定义类型别名的两种方法:typedef和using

    类型别名(type alias)是一个名字,它是某种类型的同义词.使用类型别名有很多好处,它让复杂的类型名字变得简单明了.易于理解和使用,还有助于程序员清楚地知道使用该类型的真实目的.在C++中,任何 ...

  2. C#自动实现Dll(OCX)控件注册的两种方法

    打印这篇文章 尽管MS为我们提供了丰富的.net framework库,我们的程序C#开发带来了极大的便利,但是有时候,一些特定功能的控件库还是需要由第三方提供或是自己编写.当需要用到Dll引用的时候 ...

  3. 注册Google 谷歌注册的两种方法

    ---------------------------------------------------------------------------------------------------- ...

  4. 按键精灵两种方法对大漠进行注册regsvr32

    大漠注册 时调用大漠插件的第一步,下面介绍两种注册方法 //方法1 // 判断大漠插件是否注册到系统 Function IsRegDM(sVer)Dim TmpObjSet TmpObj = Crea ...

  5. nacos实现服务注册与两种消费方式

    nacos实现服务注册与两种消费方式 运行nacos 服务注册实例 两种服务消费方式 RestTemplet Feign 测试 参考 运行nacos 预备环境:64位操作系统.64位JDK1.8+.M ...

  6. MSCOMM32控件注册的两种办法

    当我们在VC或者VB或者VS环境下基于MSCOMM控件开发的软件发布后,是不是有种很爽的感觉,可以拿到别人的电脑上运行下你的软件,可是当你移植过去后却发现软件无法点击的动(别笑,我在开发C#软件时就是 ...

  7. VB两种方法注册热键

    热键是什么东西想必大家都明白,它的应用可以大大加快我们操作的速度.有时候看一个人使用热键的频率就可以看出他对这个软件的熟悉程度.在自己的程序中使用热键同样会使操作更简便.现在我们就来谈谈vb中的两种热 ...

  8. android注册广播两种方式,Android 注册广播的两种方式对比

    Android 注册广播的两种方式对比 1.常驻型广播 常驻型广播,当你的应用程序关闭了,如果有广播信息来,你写的广播接收器同样的能接受到, 他的注册方式就是在你的应用程序中的AndroidManif ...

  9. android 函数名注册,Android JNI 函数注册的两种方式(静态注册/动态注册)

    在Android开发中,由于种种原因我们需要调用C/C++代码, 这个时候就要用到Android开发者都听说过的JNI(Java Native Interface)了, 在调用JNI相关方法之前, 要 ...

最新文章

  1. 让Updatepanel中的控件触发整个页面Postback
  2. ISA Server***检测及配置
  3. Itext实现导出PDF常用方法说明
  4. VTK:图片之ImageLuminance
  5. echarts 地图实现轮播(二)
  6. Reuse library debug in Chrome - phase2 handle success response (2)
  7. C语言函数返回1和返回0究竟哪个好?
  8. 吴恩达作业8:三层神经网络实现手势数字的识别(基于tensorflow)
  9. Mysql数据库的简单介绍
  10. 深入理解 gRPC 协议--理解protobuf/.proto/http2
  11. [poj1222]EXTENDED LIGHTS OUT(高斯消元)
  12. 超强扒站神器:SiteSucker Pro for Mac(4.1.3多语言)
  13. Spring中@DependsOn注解的作用及实现原理解析
  14. Android通过RecyclerView实现手风琴效果
  15. c语言malloc函数的用法和意义
  16. matebook14支持触摸屏吗_MateBook14:同价位一个能打的都没有(我说的是屏幕)
  17. mysql查询1970年以后出生的人_1970年属狗女一生命运,70年属狗人一生灾难有哪些...
  18. 配置git mergetool不产生*.orig文件
  19. 如何改变hr标签的颜色
  20. 客户心声 | 四川省人社厅杨玉成一行充分肯定桂溪街道劳动保障工作信息化建设平台

热门文章

  1. OpenCV视频篇——视频文件格式--视频封装格式--视频编码格式区分
  2. Redis基础入门及五大数据结构API使用
  3. npm cnpm npx nvm 区别
  4. 在线Excel转SQL工具
  5. 怎样能点亮QQ面板上更多的图标(要免费的哦)
  6. rtthread studio入门点亮LED灯
  7. nginx代理静态资源
  8. OpenMVstm32通信
  9. 2021年中国染料行业供需态势及发展趋势分析[图]
  10. 无服务器(Serverless)是PostgreSQL的未来