简单工厂模式

复制代码
 1 #ifndef SIMPLE_FACTORY_H
 2 #define SIMPLE_FACTORY_H
 3 
 4 #include <iostream>
 5 
 6 class Product
 7 {
 8 public:
 9     virtual void play(void) = 0;    // 没有定义的函数记得声明为纯虚函数
10 };
11 
12 class DVD: public Product
13 {
14 public:
15     void play(void)
16     {
17         std::cout << "now play DVD" << std::endl;
18     }
19 };
20 
21 class CD: public Product
22 {
23 public:
24     void play(void)
25     {
26         std::cout << "now play CD" << std::endl;
27     }
28 };
29 
30 class Creator
31 {
32 public:
33     enum PRODUCT_TYPE
34     {
35         TYPE_DVD,
36         TYPE_CD
37     };
38 
39     Product* factory(PRODUCT_TYPE type) {
40         switch (type) {
41         case TYPE_DVD:
42             return new DVD;
43         case TYPE_CD:
44             return new CD;
45         default:
46             return NULL;
47         }
48     }
49 };
50 
51 #endif // SIMPLE_FACTORY_H
复制代码

下面是使用的代码

复制代码
 1 #include "SimpleFactory.h"
 2 
 3 int main(void)
 4 {
 5     Creator creator;
 6     Product* dvd = creator.factory(Creator::TYPE_DVD);
 7     Product* cd = creator.factory(Creator::TYPE_CD);
 8 
 9     dvd->play();
10     cd->play();
11 
12     return 0;
13 }
复制代码

输出为

now play DVD
now play CD

 

posted @   WendellYih  阅读(185)  评论(0编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· Ollama——大语言模型本地部署的极速利器
· 使用C#创建一个MCP客户端
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· Windows编程----内核对象竟然如此简单?
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
点击右上角即可分享
微信分享提示