策略(Strategy)模式,是比较简单的一种设计模式,但它的应用却随处可见。下面模拟游戏中常用的打斗场面,来理解策略模式。在游戏中,通常有n个角色,每个角色都能发出动作:fight。每个角色都使用不同的武器,并且可以更换武器。下面是此场景简化的C++实现:
Strategy.h













































































说明:
1.因为每个武器的使用方式不同,所以将使用武器的行为封装成接口,利用此接口调用具体武器的useWeapon行为。
2.因为每个角色都有打斗,更换武器的行为,各个角色的打斗行为不同,而更换武器的行为相同,所以将setWeapon在Character中实现,而打斗行为在各个具体的角色中实现。
Strategy.cpp










































































main.cpp


































策略(Strategy)模式体现了2个重要的面向对象设计原则:
1.封装变化。
2.针对接口编程。