码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2019-12-22 16:15:29      阅读:92      评论:0      收藏:0      [点我收藏+]

标签:iostream   code   23种设计模式   create   ret   int   来源   设计   getc   

以下代码来源: 设计模式精解-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将算法封装到类中,通过组合的方式 将具体算法的实现在组合对象中实现

标签:iostream   code   23种设计模式   create   ret   int   来源   设计   getc   

原文地址:https://www.cnblogs.com/fourmi/p/12079671.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!