设计模式之策略模式

头文件

#pragma once
#include "Operation.h"  //不需要派生类的头文件

class Context
{
public:
    Context(Operation *pOperArg);
    ~Context();

    void ContextInterface();

private:
    Operation *pOper;
};

实现文件

#include "pch.h"
#include "Context.h"


Context::Context(Operation *pOperArg) : pOper(pOperArg)
{
}


Context::~Context()
{
}

void Context::ContextInterface()
{
    pOper->GetResult();
    return ;
}

基类Operation及Operation的派生类沿用之前的。

测试

#include "pch.h"
#include <iostream>
#include "Context.h"
#include "OperationAdd.h"
int main() { Operation *pOperAdd = new OperationAdd(); Context *pConAdd = new Context(pOperAdd); pOperAdd->SetNumberA(1.2); pOperAdd->SetNumberB(3.0); pConAdd->ContextInterface(); if (pOperAdd) { delete pOperAdd; } if (pConAdd) { delete pConAdd; } std::cout << "Hello World!\n"; }

策略模式体现的是对算法接口的复用。

 

从代码划分来看:

  1.Context类,调用的基类Operation。如果是算法上的变动,不会影响到Context类。

  2.Operation类的派生类(算法类),完全独立。

  3.从调用者角度看,需要Context头文件及派生类的头文件。个人感觉这样更麻烦,鸡肋。

posted @ 2019-10-17 16:21  N_zero  阅读(108)  评论(0)    收藏  举报