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

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

  • 代码示例(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 }
posted @ 2013-01-05 16:18  iThinking  阅读(210)  评论(0编辑  收藏  举报