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

本文通过一个具体例子介绍了策略模式的概念及其实现方式。策略模式允许在运行时选择算法,通过定义一系列算法并将每个算法封装起来,使得它们可以互相替换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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

例如:

 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值