(本博客旨在个人总结回顾)
1、详情:
策略模式:定义一系列算法,把它们一个个封装起来,使得它们可以相互替换。策略模式使得算法变化可独立于使用它的用户。
说明:
优点:
①算法可以自由切换。
②避免使用多重条件判断。
③扩展性良好。
缺点:
①策略类会增多。
②所有策略类都需要对外暴露。
2.1、UML类图:
2.2、例子源码
stdafx.h
// stdafx.h : 标准系统包含文件的包含文件,
// 或是经常使用但不常更改的
// 特定于项目的包含文件
//
#pragma once
#include "targetver.h"
#include <stdio.h>
#include <tchar.h>
#include <iostream>
using namespace std;
// TODO: 在此处引用程序需要的其他头文件
Strategy.h(策略接口类)
#pragma once
class Strategy
{
public:
Strategy();
virtual ~Strategy();
public:
virtual void Algorithm() = 0;
};
Strategy.cpp
#include "stdafx.h"
#include "Strategy.h"
Strategy::Strategy()
{
}
Strategy::~Strategy()
{
}
StrategyX.h(具体策略类X)
#pragma once
#include "Strategy.h"
class StrategyX :
public Strategy
{
public:
StrategyX();
~StrategyX();
public:
void Algorithm();
};
StrategyX.cpp
#include "stdafx.h"
#include "StrategyX.h"
StrategyX::StrategyX()
{
}
StrategyX::~StrategyX()
{
}
void StrategyX::Algorithm()
{
cout << "算法X实现!" << endl;
}
StrategyY.h(具体策略类Y)
#pragma once
#include "Strategy.h"
class StrategyY :
public Strategy
{
public:
StrategyY();
~StrategyY();
public:
void Algorithm();
};
StrategyY.cpp
#include "stdafx.h"
#include "StrategyX.h"
StrategyX::StrategyX()
{
}
StrategyX::~StrategyX()
{
}
void StrategyX::Algorithm()
{
cout << "算法X实现!" << endl;
}
Context.h
#pragma once
#include "Strategy.h"
class Context
{
public:
Context(Strategy* pStrategy);
~Context();
public:
void Operation();
private:
Strategy* m_pStrategy;
};
Context.cpp
#include "stdafx.h"
#include "Context.h"
Context::Context(Strategy* pStrategy)
: m_pStrategy(pStrategy)
{
}
Context::~Context()
{
if (m_pStrategy != NULL)
{
delete m_pStrategy;
m_pStrategy = NULL;
}
}
void Context::Operation()
{
if (m_pStrategy != NULL)
{
m_pStrategy->Algorithm();
}
}
调用代码
StrategyPatternMemo.cpp
// StrategyPatternMemo.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "Context.h"
#include "StrategyX.h"
#include "StrategyY.h"
int _tmain(int argc, _TCHAR* argv[])
{
Context* pContext = new Context(new StrategyX());
pContext->Operation();
delete pContext;
pContext = new Context(new StrategyY());
pContext->Operation();
delete pContext;
system("pause");
return 0;
}