设计模式-Strategy Strategy将算法封装到类中,通过组合的方式 将具体算法的实现在组合对象中实现
以下代码来源: 设计模式精解-GoF 23种设计模式解析附C++实现源码
//strategy.h
#pragma once class Strategy { public: Strategy(); virtual ~Strategy(); virtual void AlgrithmInference() = 0; protected: private: }; class ConcreateStrategyA :public Strategy { public: ConcreateStrategyA(); virtual ~ConcreateStrategyA(); void AlgrithmInference(); protected: private: }; class ConcreateStrategyB :public Strategy { public: ConcreateStrategyB(); virtual ~ConcreateStrategyB(); void AlgrithmInference(); protected: private: };
//strategy.cpp
#include"strategy.h" #include<iostream> Strategy::Strategy(){} Strategy::~Strategy() { std::cout << "~Strategy....." << std::endl; } void Strategy::AlgrithmInference() { } ConcreateStrategyA::ConcreateStrategyA(){} ConcreateStrategyA::~ConcreateStrategyA() { std::cout << "~ConcreateStrategyA" << std::endl; } void ConcreateStrategyA::AlgrithmInference() { std::cout << "test ConcreateStrategyA" << std::endl; } ConcreateStrategyB::ConcreateStrategyB(){} ConcreateStrategyB::~ConcreateStrategyB() { std::cout << "~ConcreateStrategyB" << std::endl; } void ConcreateStrategyB::AlgrithmInference() { std::cout << "test ConcreateStrategyB...." << std::endl; }
//Context.h
#pragma once class Strategy; //Strategy模式与Template模式的根本区别是 Strategy通过 组合(委托)方式实现算法异构,Template使用继承的方式 class Context { public: Context(Strategy* stg); virtual ~Context(); void DoAction(); protected: private: Strategy* _stg; };
//Context.cpp
#include"Context.h" #include"strategy.h" #include<iostream> Context::Context(Strategy* stg) { _stg = stg; } Context::~Context() { if (!_stg) delete _stg; } void Context::DoAction() { _stg->AlgrithmInference(); }
//main.cpp
#include"Context.h" #include"strategy.h" #include<iostream> #include<string> int main(int args, char* argv) { Strategy* ps = new ConcreateStrategyA(); Context* pc = new Context(ps); pc->DoAction(); if (NULL != pc) delete pc; getchar(); return 0; }