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 }
  • 相关阅读:
    工作笔记(一)
    如何修改mindmanager默认字体为微软雅黑
    彻底解决zend studio 下 assignment in condition警告
    PHP5.2至5.6的新增功能详解
    ThinkPHP中的模型命名
    12大网站建设技巧 让访客信任你
    CentOS 7.0编译安装Nginx1.6.0+MySQL5.6.19+PHP5.5.14
    几种不错的编程字体
    大型网站的灵魂——性能
    MySQL: InnoDB 还是 MyISAM?
  • 原文地址:https://www.cnblogs.com/dahai/p/2846156.html
Copyright © 2011-2022 走看看