하나의 클래스가 많은 행동들을 정의하고,
이런 행동들이 그 클래스의 연산 안에서 복잡한 다중 조건문의 모습을 취할 때,
많은 조건문보다는 행동 각각을 전략(Strategy) 클래스로 만들고,
동적으로 행동의 변경이 필요한 경우 전략(Strategy)을 바꾸어 주는 것으로
알고리즘을 다양하게 변경할 수 있게 해주는 패턴이다.
//class형
class ProductStrategy {//추상클레스
print() {
console.log('Error : auth() must be implement')
}
}
class Block extends ProductStrategy {
print(quantity) {
return quantity * 5000 + '원'
}
}
class Flower extends ProductStrategy {
print(quantity) {
return quantity * 1000 + '원'
}
}
class Error extends ProductStrategy {
}
class ProductProgram {
constructor (product) {
this.product = product
}
calculrate (quantity) {
return this.product.print(quantity)
}
}
const block = new Block()
const flower = new Flower()
const err = new Error()
const programB = new ProductProgram(block)
const programF = new ProductProgram(flower)
const programE = new ProductProgram(err)
programB.calculrate(3) //15000원
programF.calculrate(3) //3000원
programE.calculrate(3) //'Error : auth() must be implement'
function WaterMelon () {
this.getPrice = function(quantity){
return quantity * 4000
}
}
function Orange () {
this.getPrice = function(quantity){
return quantity * 2000
}
}
function FruitPrice () {
this.kind
this.setFruitChain = function(kind){
this.kind = kind
}
this.calc = function(quantity) {
return this.kind.getPrice(quantity)
}
}
const waterMelon = new WaterMelon()
const orange = new Orange()
const fruitPrice = new FruitPrice()
fruitPrice.setFruitChain(waterMelon)
fruitPrice.calc(4) //16000
fruitPrice.setFruitChain(orange)
fruitPrice.calc(2) //4000
FP in JS (자바스크립트로 접해보는 함수형 프로그래밍) - 함수 컴포지션, 커링
techblog
디자인패턴 - 전략 패턴(Strategy Pattern) in Javascript
전략 패턴