전략 패턴(Strategy Pattern)은 객체가 할 수 있는 행위(알고리즘)들을 클래스로 캡슐화하고, 동적으로 행위를 자유롭게 교체(Swap)할 수 있게 해주는 패턴입니다. RPG 게임 캐릭터가 무기를 검에서 활로 바꾸면 공격 동작이 완전히 달라지는 것처럼, 수많은 if-else문을 쓰지 않고도 '전략 인터페이스'를 조립(Composition)하는 방식으로 결합도를 낮춥니다.
1. 전략 패턴 구조 (Strategy UML)
Context는 구체적인 전략(Concrete Strategy)이 무엇인지 알 필요가 없습니다. 오직 Strategy 인터페이스에만 의존하며, 런타임에 외부에서 전략 객체를 주입(DI)받아 실행합니다.
2. 상속(Inheritance) 대신 위임(Delegation)
💡 OCP(개방-폐쇄 원칙) 완벽 준수
만약 '마법 지팡이(MagicStrategy)'라는 새로운 무기가 추가되어도, Context(Player) 코드는 단 한 줄도 수정할 필요가 없습니다. 새로운 Strategy 클래스를 만들고 setStrategy()로 주입해주기만 하면 됩니다. 이처럼 알고리즘 캡슐화를 통해 상속보다 훨씬 유연한 구조를 만들 수 있습니다.
// 📂 Strategy.js (JavaScript)
// 자바스크립트는 일급 함수(First-Class Function)를 지원하므로,
// 객체(클래스)를 쓰지 않고 함수만으로도 전략 패턴을 아주 쉽게 구현할 수 있습니다.
// 전략(Strategy) 객체들
const swordStrategy = {
attack: () => console.log("🗡️ 검으로 강하게 벱니다! (데미지: 50)")
};
const bowStrategy = {
attack: () => console.log("🏹 활로 멀리서 쏩니다! (데미지: 30)")
};
const magicStrategy = {
attack: () => console.log("🔥 화염 마법을 시전합니다! (데미지: 100)")
};
// 컨텍스트(Context)
class Player {
constructor(name) {
this.name = name;
this.weaponStrategy = swordStrategy; // 기본 무기
}
setWeapon(strategy) {
this.weaponStrategy = strategy;
console.log(`\n[시스템] ${this.name}의 무기가 변경되었습니다.`);
}
attack() {
console.log(`${this.name}의 공격!`);
this.weaponStrategy.attack(); // 전략 위임
}
}
// 📂 main.js
const hero = new Player("용사 김코딩");
hero.attack(); // 기본 검 공격
hero.setWeapon(bowStrategy); // 런타임에 활로 변경!
hero.attack();
hero.setWeapon(magicStrategy); // 런타임에 마법으로 변경!
hero.attack();