策略模式作为行为型设计模式中的一种,主要封装相同功能的不同实现算法,用于在用户程序内部灵活切换。对用户来说能够快速替换对应的算法,能够让算法的实现独立于使用的用户。
基本的UML类图如下:
#include <iostream>
#include <string>
using namespace std;
class Cache {
public:
virtual void use_cache() = 0;
virtual ~Cache(){}
};
class LRU: public Cache {
public:
LRU(){}
void use_cache() {
cout << "Use LRU Cache " << endl;
}
};
class Clock: public Cache {
public:
Clock(){}
void use_cache() {
cout << "Use Clock Cache " << endl;
}
};
class Strategy {
public:
//explicit Strategy(Cache *cache, string name): _cache(cache),res(name) {}
Strategy(Cache *cache, string name): _cache(cache),res(name) {}
void set_cache(Cache *cache) {
this -> _cache = cache;
}
void use_cache() {
cout << "strategy name is : "<< res << endl;
_cache->use_cache();
}
private:
Cache *_cache;
string res;
};
int main() {
LRU *caheA = new LRU();
Clock *caheB = new Clock();
Strategy stra(caheA, "stra");
Strategy strb(caheB, "strb");
stra.use_cache();
strb.use_cache();
cout << "Change the strategy Quickly" << endl;
stra.set_cache(caheB);
strb.set_cache(caheA);
stra.use_cache();
strb.use_cache();
return 0;
}
strategy name is : stra
Use LRU Cache
strategy name is : strb
Use Clock Cache
Change the strategy Quickly
strategy name is : stra
Use Clock Cache
strategy name is : strb
Use LRU Cache