c

策略模式

策略模式是指定义一系列的算法,把它们单独封装起来,并且使它们可以互相替换,使得算法可以独立于使用它的客户端而变化,也是说这些算法所完成的功能类型是一样的,对外接口也是一样的,只是不同的策略为引起环境角色环境角色表现出不同的行为。

2.2 使用函数指针实现策略模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include "stdafx.h"
#include <iostream>

using namespace std;

void adcHurt()
{
cout << "Adc hurt" << endl;
}
void apcHurt()
{
cout << "Apc hurt" << endl;
}

class soldier
{
public:
typedef void(*Function) ();
soldier(Function fun) :m_fun(fun) {}
void attack()
{
m_fun();
}
private:
Function m_fun;
};

int main()
{
soldier* yase = new soldier(adcHurt);
yase->attack();
delete yase;
yase = nullptr;
cin.get();
return 0;
}