# 设计模式读书笔记：Strategy（策略）

Context

#include <iostream>
#include "Strategy.h"

namespace NS_STRATEGY {

class Context {
public:
Context() : _strategy(0) {}
virtual ~Context() {}
void contextInterface(void)
{
int a, b;
std::cout << "a=";
std::cin >> a;
std::cout << "b=";
std::cin >> b;

if (_strategy)
_strategy->algorithmInterface(a, b);
}

void setStrategy(Strategy *strategy)
{
_strategy = strategy;
}

private:
Strategy *_strategy;
};

} /* namespace NS_STRATEGY */
Strategy

namespace NS_STRATEGY {

class Strategy {
public:
Strategy() {}
virtual ~Strategy() {}
virtual void algorithmInterface(int a, int b) = 0;
};

} /* namespace NS_STRATEGY */
ConcreteStrategyA

#include <iostream>
#include "Strategy.h"

namespace NS_STRATEGY {

class ConcreteStrategyA : public Strategy
{
public:
ConcreteStrategyA() {}
virtual ~ConcreteStrategyA() {}
virtual void algorithmInterface(int a, int b)
{
std::cout << "a+b = " << a+b << std::endl;
}
};

} /* namespace NS_STRATEGY */
ConcreteStrategyB

#include <iostream>
#include "Strategy.h"

namespace NS_STRATEGY {

class ConcreteStrategyB : public Strategy
{
public:
ConcreteStrategyB() {}
virtual ~ConcreteStrategyB() {}
virtual void algorithmInterface(int a, int b)
{
std::cout << "a-b = " << a-b << std::endl;
}
};

} /* namespace NS_STRATEGY */
main

#include "Strategy/Context.h"
#include "Strategy/ConcreteStrategyA.h"
#include "Strategy/ConcreteStrategyB.h"
using namespace NS_STRATEGY;
int main(void)
{
Context c;
ConcreteStrategyA csa;
ConcreteStrategyB csb;
c.setStrategy(&csa);
c.contextInterface();
c.setStrategy(&csb);
c.contextInterface();
}

• 本文已收录于以下专栏：

举报原因： 您举报文章：设计模式读书笔记：Strategy（策略） 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)