初学设计模式之策略模式

策略模式的代码例子

 1 //策略模式
 2 #include<iostream>
 3 using namespace std;
 4 
 5 class strategy
 6 {
 7 public:
 8 virtual void Do()
 9 {};
10 };
11 class strategy1:public strategy
12 {
13 public:
14     void Do()
15     {
16         cout<<"策略1"<<endl;
17     }
18 };
19 class strategy2:public strategy
20 {
21 public:
22     void Do()
23     {
24         cout<<"策略2"<<endl;
25     }
26 };
27 class Context
28 {
29 private:
30     strategy *m_strategyPtr;
31 public:
32     Context(strategy *_strategyPtr)
33     {
34         m_strategyPtr=_strategyPtr;
35     };
36     void exec()
37     {
38         m_strategyPtr->Do();
39     };
40 };
41 int main()
42 {
43    strategy1 m_Strategy1;
44    Context m_Context(&m_Strategy1);
45    m_Context.exec();
46    strategy1 m_Strategy2;
47     Context m_Context2(&m_Strategy2);
48    m_Context2.exec();
49    getchar();
50    return 0;
51 };

 

posted on 2019-11-09 23:14  宏择一城  阅读(148)  评论(0编辑  收藏  举报

导航