• 设计模式——策略模式(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 }
  • 相关阅读:
    Simple DirectMedia Layer常用API总结
    [游戏复刻] Super Mario Brothers(1985. Famicom)
    [游戏复刻] 2048(2014. Android)
    图的结构以及寻路算法的c实现
    散列查找的C实现
    【游戏编程从0开始】一、基本结构
    C++中const关键字用法总结
    C标准库常用函数概要
    字符串表达式计算器的设计
    初探数据结构
  • 原文地址:https://www.cnblogs.com/dahai/p/2846156.html
Copyright © 2020-2023  润新知