设计模式——策略模式(Strategy)

  • 定义:封装一系列算法, 使其可相互替换。
  • 本模式使算法可独立于客户而变化。
  • UML
    设计模式——策略模式(Strategy)

  • 代码示例(C++)

1 //==========================================
 2 //strategy.h
 3 //==========================================
 4 #pragma once
 5 
 6 class Strategy;
 7 class Context
 8 {
 9 public:
10     Context(Strategy* pStrategy);
11     ~Context();
12     void SetStrategy(Strategy* pStrategy);
13     void Request();
14 private:
15     Strategy* m_pStrategy;
16 };
17 
18 class Strategy
19 {
20 public:
21     virtual ~Strategy(){}
22     virtual void AlgorithmInterface() = 0;
23 };
24 
25 class ConcreteStrategyA : public Strategy
26 {
27 public:
28     void AlgorithmInterface();
29 };
30 
31 class ConcreteStrategyB : public Strategy
32 {
33 public:
34     void AlgorithmInterface();
35 };
36 
37 //==========================================
38 //strategy.cpp
39 //==========================================
40 #include "strategy.h"
41 #include <iostream>
42 using namespace std;
43 
44 Context::Context(Strategy* pStrategy)
45     :m_pStrategy(pStrategy)
46 {
47 }
48 
49 Context::~Context()
50 {
51     delete m_pStrategy;
52 }
53 
54 void Context::SetStrategy(Strategy* pStrategy)
55 {
56     delete m_pStrategy;
57     m_pStrategy = pStrategy;
58 }
59 
60 void Context::Request()
61 {
62     if (NULL != m_pStrategy)
63     {
64         m_pStrategy->AlgorithmInterface();
65     }
66 }
67 
68 void ConcreteStrategyA::AlgorithmInterface()
69 {
70     cout<<"ConcreteStrategyA::AlgorithmInterface()"<<endl;
71 }
72 
73 void ConcreteStrategyB::AlgorithmInterface()
74 {
75     cout<<"ConcreteStrategyB::AlgorithmInterface()"<<endl;
76 }
77 
78 int main()
79 {
80     Context ctx(new ConcreteStrategyA);
81     ctx.Request();
82     ctx.SetStrategy(new ConcreteStrategyB);
83     ctx.Request();
84 
85     return 0;
86 }
  • 原文链接: https://www.cnblogs.com/dahai/archive/2013/01/05/2846156.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/74586

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月9日 下午4:28
下一篇 2023年2月9日 下午4:28

相关推荐