乐趣区

策略模式

简介

策略模式,定义了一个算法族,并且封装了每一个算法,使它们可以互相替换。策略模式让算法与使用它的客户端独立的变化。

UML 类图

示例

策略模式比较常见。人总要学习,正如在开篇中所说,通过读可以,写效果更好,能够通过分享或者教会别人可能会更有效。
策略相关类,strategy.h

#ifndef STRATEGY_H
#define STRATEGY_H
#include <iostream>

using namespace std;
class CLearning
{
public:
    virtual void Learn() = 0;};

class CReading:public CLearning
{
public:
    void Learn()
    {cout<<"Learn by Reading."<<endl;}
};

class CWriting:public CLearning
{void Learn()
    {cout<<"Learn by Writing."<<endl;}
};

class CTeaching:public CLearning
{void Learn()
    {cout<<"Learn by Teaching."<<endl;}
};

class CLearningContext
{
public:
    CLearningContext(CLearning* pLearning)
    {m_pLearning = pLearning;}
    void Learn()
    {m_pLearning->Learn();
    }
private:
    CLearning* m_pLearning;
};
#endif

客户端调用,main.cpp

#include "strategy.h"

#define SAFE_DELETE(p) if(p){delete (p); (p) = NULL;}
int main(int argc, char* argv[])
{
    CWriting* pWriting = new CWriting;
    CLearningContext* pContext = new CLearningContext(pWriting);
    pContext->Learn();
    SAFE_DELETE(pWriting);
    SAFE_DELETE(pContext);
    return 0;
}
退出移动版