设计模式-Strategy Strategy将算法封装到类中,通过组合的方式 将具体算法的实现在组合对象中实现

Posted fourmi

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了设计模式-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;
}

以上是关于设计模式-Strategy Strategy将算法封装到类中,通过组合的方式 将具体算法的实现在组合对象中实现的主要内容,如果未能解决你的问题,请参考以下文章

策略模式-Strategy

设计模式 之 策略(Strategy)模式

38面向对象设计模式之策略模式(Strategy)

策略模式(Strategy

Strategy模式详解--设计模式(13)

策略模式(strategy)