策略模式意图将解决问题的算法分别封装成一个个对象的形式,并使这些算法对象相互间可被替换。模式比较简单,对于策略对象结构的设计,可抽象一个抽象基类,并定义好相关算法(纯)虚接口,并由各种具体的实现算法子类实现即可。因此模式的类关系结构图参考如下:

【行为型】Strategy模式

    模式编码结构参考如下:

 1 namespace strategy
 2 {
 3     class IAbstractStrategy
 4     {
 5     public:
 6         // some code here........
 7         virtual void executeAlgorithm() = 0;
 8 
 9     };//class IAbstractStrategy
10 
11     class ConcreteStrategy1 : public IAbstractStrategy
12     {
13     public:
14         // some code here........
15         virtual void executeAlgorithm() override {
16             // some code here........
17             // execute real algorithm code.
18             // some code here........
19         }
20 
21     };//class ConcreteStrategy1
22 
23     class ConcreteStrategy2 : public IAbstractStrategy
24     {
25     public:
26         // some code here........
27         virtual void executeAlgorithm() override {
28             // some code here........
29             // execute real algorithm code.
30             // some code here........
31         }
32 
33     };//class ConcreteStrategy2
34 
35     class Context
36     {
37     public:
38         // some code here........
39         void doSomething(IAbstractStrategy* pStrategy) {
40             // e.g
41             if (nullptr != pStrategy) {
42                 pStrategy->executeAlgorithm();
43             }
44         }
45 
46     };
47 
48 }//namespace strategy
Strategy模式编码结构参考

相关文章:

  • 2021-06-22
  • 2021-11-23
  • 2022-12-23
  • 2021-11-13
  • 2022-12-23
  • 2021-07-14
  • 2021-05-24
  • 2022-12-23
猜你喜欢
  • 2021-11-21
  • 2022-01-09
  • 2021-09-24
  • 2022-01-10
  • 2021-06-19
  • 2022-03-05
  • 2022-01-07
相关资源
相似解决方案