策略模式介绍
GoF 5.9节介绍了策略(Strategy)模式。目的是:定义一系列的算法,把它们封装起来,并使它们可相互替换,使算法独立于它的客户而变化。
ASD 14.2节介绍了策略模式。
策略模式实例 - 地图应用中计算里程时耗
说明
地图应用中,通常会计算两点间的通行时间,如步行、公交、自驾。不同的工具走相同的路程有不同的时间开销。
C++代码
定义地图类:
class Map { private: class Strategy* _strategy; public: Map() { _strategy = NULL; } int time_costs(int distance); void set_strategy(Strategy* s); };
定义策略基类(即算法基类),并把地图中的计算时耗功能委托给策略类:
class Strategy { public: virtual int time_costs(int distance) = 0; }; int Map::time_costs(int distance) { return _strategy->time_costs(distance); } void Map::set_strategy(Strategy* s) { delete _strategy; _strategy = s; }
定义策略类的基类:
class Walk : public Strategy { public: virtual int time_costs(int distance) { return (15 * distance); } }; class Car : public Strategy { public: virtual int time_costs(int distance) { return (0.8 * distance); } };
测试:
int main() { Map* map = new Map; map->set_strategy(new Walk); cout << "time costs of 50km with walk: " << map->time_costs(50) << " seconds\n"; map->set_strategy(new Car); cout << "time costs of 50km with car: " << map->time_costs(50) << " seconds\n"; return 0; }
对比策略模式和其他设计模式
策略模式和状态模式的区别是策略模式没有回指向上下文的引用。