-
전략패턴
: 객체 지향 프로그래밍에서 사용되는 디자인 패턴 중 하나로 알고리즘을 캡슐화 하고 서로 교환 가능하도록 만드는 패턴이다.
문제를 해결하는 여러 알고리즘들이 있을 때 이들을 동일한 인터페이스를 사용하여 클라이언트에게 제공하고 실행 시점에 알고리즘을 변경 할 수 있게 한다. 즉 쉽게 말해 여러가지 전략 을 하나의 컨텍스트안에 넣어 사용자가 사용하기 쉽게 선택하거나 교환 해주는 것이다.
//전략 인터페이스 class SoundStrategy { makeSound(); } // 강아지가 짖는 소리 전략 class DogSoundStrategy extends SoundStrategy { makeSound() { return "멍멍!"; } } // 고양이가 울렁거리는 소리 전략 class CatSoundStrategy extends SoundStrategy { makeSound() { return "야옹~"; } } // 오리가 꽥꽥거리는 소리 전략 class DuckSoundStrategy extends SoundStrategy { makeSound() { return "꽥꽥!"; } } //컨텍스트 class Animal { constructor(soundStrategy) { this.soundStrategy = soundStrategy; } makeSound() { return this.soundStrategy.makeSound(); } } // 클라이언트 const dog = new Animal(new DogSoundStrategy()); console.log(dog.makeSound()); // Output: "멍멍!" const cat = new Animal(new CatSoundStrategy()); console.log(cat.makeSound()); // Output: "야옹~" const duck = new Animal(new DuckSoundStrategy()); console.log(duck.makeSound()); // Output: "꽥꽥!"