zoukankan      html  css  js  c++  java
  • 设计模式——策略模式(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 }
  • 相关阅读:
    硬币游戏 Project Euler 232
    屏幕空间的近似全局光照明(Approximative Global Illumination in Screen Space)
    四维之美
    vertex texture fetching in HLSL, and heightfield normal calculation
    一个VS小插件(跳出括号)
    我的算法书籍收藏
    Algorithms.算法概论.习题答案
    UML用例图教程详解
    大连理工大学软件学院博客地址
    快递查询API,我推荐“爱快递”
  • 原文地址:https://www.cnblogs.com/dahai/p/2846156.html
Copyright © 2011-2022 走看看