Design patterns — strategy Link to heading
Strategy pattern, sometimes also referred as policy pattern, can perform different strategies (or policies) of behavior at runtime. Its…
Design pattern — strategy Link to heading
The Strategy pattern, also known as the policy pattern, enables the implementation of different strategies or policies for behavior at runtime. It achieves this by composing a behavior object. In this pattern, behavior can be considered as a functionality, while strategies or policies represent variations of that functionality.
A great intuitive example to understand the strategy pattern is a first-person shooting (FPS) game. In this game, each player is represented by a Player object that possesses a shoot() method. The implementation of the shoot() method relies on the player’s primary weapon, which can change during gameplay (runtime). As a result, the shoot() method delegates its strategy to the fire() method of the weapon held by the Player object (composition).
trait Weapon {
fn fire(&self);
}
struct M16Rifle;
impl Weapon for M16Rifle {
fn fire(&self) {
println!("dut dut");
}
}
struct Bazuka;
impl Weapon for Bazuka {
fn fire(&self) {
println!("Kablam!!");
}
}
struct Player {
weapon: Box<dyn Weapon>,
}
impl Player {
fn new(weapon: Box<dyn Weapon>) -> Self {
Self { weapon }
}
fn change_weapon(&mut self, weapon: Box<dyn Weapon>) {
self.weapon = weapon;
}
fn shoot(&self) {
self.weapon.fire(); // just delegate to Weapon
}
}
fn main() {
let mut player = Player::new(Box::new(M16Rifle));
player.shoot(); // dut dut
player.change_weapon(Box::new(Bazuka));
player.shoot(); // Kablam!!
}
The key concept behind the strategy pattern is the ability to define a trait or interface for the behavior of interest. As humans, we are accustomed to associating behaviors with actions rather than objects. Typically, objects are perceived as nouns rather than verbs. What makes the FPS example effective is the easy association between the action of firing and the weapon itself. This association allows for the intuitive creation of a Weapon trait, which determines the strategy for the shoot() method of the Player.