Strategy Pattern
Swap behaviors at runtime.
Strategy Pattern
Analogy: pattern
The Strategy Pattern is like a Video Game Inventory.
You can equip a Sword, a Bow, or a Shield.
When you press "Attack", the character does something different depending on what is equipped. You don't have to create a new character to change weapons.
The Battle Bot
Equip a strategy and see how the bot behaves.
- Melee: Swings a sword.
- Ranged: Shoots an arrow.
- Defensive: Raises a shield.
Battle Bot (Strategy Pattern)
1. Equip Strategy
// Ready for battle...
The Code
Define a common interface (Weapon) and implement different strategies.
Java Example
Switch language in Navbar
interface Weapon { void use(); }
class Sword implements Weapon {
public void use() { System.out.println("Swing!"); }
}
class Robot {
private Weapon weapon;
public void setWeapon(Weapon w) { this.weapon = w; }
public void attack() { weapon.use(); }
}
Up Next
Class Relationships