🕊️ SWIFT ENCHANTMENTS DIFFICULTY: Adept Behavioral

The Strategy Pattern

Selecting a magical algorithm at runtime.

✧ GANG OF FOUR LINEAGE & ARCANUM ✧
GOF DESIGN PATTERN: Strategy
ARCANUM SCHOOL: Divination // Tactics
SCRIBE / ARCHON: Joshua Edward McLaughlin Cox
CANONICAL REGISTRATION:
// SWIFT PATTERN //
protocol CombatStrategy {
    func executeAttack()
}
class AggressiveStrategy: CombatStrategy {
    func executeAttack() { print("Casting Fireball") }
}
class DefensiveStrategy: CombatStrategy {
    func executeAttack() { print("Casting Shield") }
}
class Duelist {
    var strategy: CombatStrategy
    init(strategy: CombatStrategy) { self.strategy = strategy }
    func fight() { strategy.executeAttack() }
}

The Strategy: The Duelist’s Choice

With the Strategy pattern, a Duelist can seamlessly swap between an AggressiveStrategy and a DefensiveStrategy mid-duel.

Runic Tags: #swift #design-pattern #behavioral