C++模式学习------策略模式

news/2024/7/24 5:02:07 标签: c/c++

当遇到同一个对象有不同的行为,方法,为管理这些方法可使用策略模式。

策略模式就是对算法进行包装,是把使用算法的责任和算法本身分割开来。通常把一个系列的算法包装到一系列的策略类里面,这些类继承一个抽象的策略类。使用这些算法的时候,只需要调用子类即可。

例如:

 1 class LearnTool
 2 {
 3 public:
 4     void virtual useTool() = 0;
 5 };
 6 
 7 class BookTool:public LearnTool
 8 {
 9 public:
10     void useTool()
11     {
12         cout << "Learn by book !" << endl;
13     }
14 };
15 
16 class ComputerTool:public LearnTool
17 {
18 public:
19     void useTool()
20     {
21         cout << "Learn by computer !" << endl;
22     }
23 };
24 
25 class Person
26 {
27 public:
28     Person()
29     {
30         tool = 0;
31     }
32     void setTool(LearnTool *w)
33     {
34         this->tool = w;
35     }
36     void virtual Learn() = 0;
37 protected:
38     LearnTool *tool;
39 };
40 
41 class Tom:public Person
42 {
43 public:
44     void Learn()
45     {
46         cout << "The Tom:" ;
47         if ( this->tool == NULL)
48         {
49             cout << "You have`t tool to learn !" << endl;
50         }
51         else
52         {
53             tool->useTool();
54         }
55     }
56 };
57 int main()
58 {
59     LearnTool *book = new BookTool();
60     LearnTool *computer = new ComputerTool();
61 
62     Person *tom = new Tom();
63 
64     tom->Learn();
65     cout << endl;
66 
67     tom->setTool(book);
68     tom->Learn();
69     cout << endl;
70 
71     tom->setTool(computer);
72     tom->Learn();
73 
74     return 0;
75 }

 

转载于:https://www.cnblogs.com/tyche116/p/8580992.html


http://www.niftyadmin.cn/n/1558131.html

相关文章

js 根据开始时间计算距今 -- 时分秒

方法一 dayCha(startime, endime) {startime startime.replace(new RegExp("-", "gm"), "/"); //转换-变为/var start new Date(startime);var startYear start.getFullYear(); //开始年份var startMonth start.getMonth() 1; //开始月份v…

利用maven install jar到项目当中

接着上面利用maven打好的jar包。把刚刚打好的包放入其他项目当中怎么办&#xff1f; 只需要在相同的目录下执行mvn install&#xff0c;maven会自动把jar放到本地仓库中。 这样&#xff0c;原先maven项目中缺少依赖的地方就不会报错了。转载于:https://www.cnblogs.com/zacky31…

natapp内网穿透

首先先下载 natapp下载地址 比较尴尬的是&#xff0c;下载不了 问题是http 不行&#xff0c;将url复制出来&#xff0c;改为https 就好了 下载后&#xff0c;解压&#xff0c;然后把解压出来的文件放到一个目录里 注册、创建 mac运行下面两步 进入到目录后输入下面命令行 ch…

JAVA中基本数据类型和引用数据类型区别

一、8种基本数据类型&#xff1a; byte&#xff1a;Java中最小的数据类型 在内存中占8位(bit) 1个字节 取值范围-128~127 默认值0 short&#xff1a;短整型 在内…

关于mete标签 description、keywords

description 标签中的 meta: description 标签一般为长度为160字符的文本&#xff0c;用于介绍该页面的内容。 平常多被搜索引擎截取网页简介用 <meta namedescription content"此处填写--介绍该页面的内容">keywords 关键字 meta&#xff08;标签&#xff0…

vue字符串中<br/>换行问题

作用及定义 pre 标签可定义预格式化的文本。 被包围在 pre 标签 元素中的文本通常会保留空格和换行符。而文本也会呈现为等宽字体。 示例 用 pre 标签把字符串包起来&#xff0c;同时br换\n <template><section class"wrap"><h4 >示例&#x…

数据库MySQL的性能基线收集及压力测试

建立基线的作用&#xff1a;计算机科学中&#xff0c;基线是项目储存库中每个工件版本在特定时期的一个“快照”。 比如我们现在有并发事物&#xff0c;那么在某时刻发起一个事物会产生当前数据的快照&#xff0c;那么这个快照就相当理解为一个基线&#xff0c;那么所谓的性能数…