Henkk

导航

设计模式学习之----策略模式

策略模式:定义一系列的算法,把它们一个个封装起来,并且使它们可相互替换。接口和实现进行了隔离。

大体实现:基类定义接口子类实现算法,运用多态,运行时调用不同的算法。

 1 #include <iostream>
 2 #include <string>
 3 
 4 using namespace std;
 5 class Strategy
 6 {
 7 public:
 8     virtual void crypt() = 0;
 9 };
10 
11 class AES :public Strategy
12 {
13 public:
14     virtual void crypt()
15     {
16         cout << "AES加密算法" << endl;
17     }
18 };
19 
20 class DES :public Strategy
21 {
22 public:
23     virtual void crypt()
24     {
25         cout << "DES加密算法" << endl;
26     }
27 };
28 
29 //编程的对象,涉及的接口都依赖于抽象
30 class Context
31 {
32 public:
33     void setStrategy(Strategy *strategy)
34     {
35         m_strategy = strategy;
36     }
37     void myOperator()
38     {
39         m_strategy->crypt();
40     }
41 private:
42     Strategy *m_strategy;
43 };
44 
45 
46 int main()
47 {
48     Context *context = new Context; //编程对象
49     Strategy *strategy = nullptr;
50     strategy = new AES;
51     context->setStrategy(strategy);
52     context->myOperator();
53     delete context;
54     delete strategy;
55     return system("pause");
56 }

 

posted on 2020-05-22 11:40  Henkk  阅读(152)  评论(0编辑  收藏  举报