定義
策略模式:定義算法族,分別封裝起來(lái),讓它們之間可以互相替換,此模式讓算法的變化獨(dú)立于使用算法的客戶
策略模式的核心的“策略”兩個(gè)字,什么是策略呢,我的理解是策略是可以隨時(shí)更換的,這樣操作可以很靈活,比如我在玩CS的時(shí)候(假設(shè)我身上已經(jīng)擁有很多武器了):
- 如果敵人在遠(yuǎn)處,那我就使用阻擊槍瞄準(zhǔn),一槍爆頭!
- 如果敵人在迅速靠近,那我就切換AK,一頓掃射!
- 如果敵人已經(jīng)到了身邊,用槍是很難瞄準(zhǔn),那我就切換小刀,一頓亂砍!
寫一個(gè)武器的接口,所有武器都需要實(shí)現(xiàn)這個(gè)接口:
// 武器接口
interface IWeapon {
fire(): void,
description(): string,
}
阻擊槍的實(shí)現(xiàn)
// 阻擊槍
class Sniper implements IWeapon {
fire() {
console.log(`使用${this.description()}一槍爆頭!`)
}
description(): string {
return '阻擊槍'
}
}
AK的實(shí)現(xiàn)
// AK
class AK implements IWeapon {
fire() {
console.log(`使用${this.description()}一頓掃射!`)
}
description(): string {
return 'AK'
}
}
小刀的實(shí)現(xiàn)
// 小刀
class Knife implements IWeapon {
fire() {
console.log(`使用${this.description()}一頓亂砍!`)
}
description(): string {
return '小刀'
}
}
三種武器都實(shí)現(xiàn)了IWeapon接口,現(xiàn)在寫一個(gè)玩家類
// 玩家
class Player {
weapon?: IWeapon
setWeapon(weapon: IWeapon) {
this.weapon = weapon
console.log(`切換武器:${weapon.description()}`)
}
fire() {
this.weapon?.fire()
}
}
使用方式:
// 擁有的武器
const sniper: IWeapon = new Sniper()
const ak: IWeapon = new AK()
const knife: IWeapon = new Knife()
// 一個(gè)玩家
const p = new Player()
// 如果敵人在遠(yuǎn)處,那我就使用阻擊槍瞄準(zhǔn),一槍爆頭!
p.setWeapon(sniper)
p.fire()
// 如果敵人在迅速靠近,那我就切換AK,一頓掃射!
p.setWeapon(ak)
p.fire()
// 如果敵人已經(jīng)到了身邊,用槍是很難瞄準(zhǔn),那我就切換小刀,一頓亂砍!
p.setWeapon(knife)
p.fire()
輸出結(jié)果:
[LOG]: 切換武器:阻擊槍
[LOG]: 使用阻擊槍一槍爆頭!
[LOG]: 切換武器:AK
[LOG]: 使用AK一頓掃射!
[LOG]: 切換武器:小刀
[LOG]: 使用小刀一頓亂砍!
原則:
- 封裝變化
- 多用組合,少用繼承
- 針對(duì)接口編程,不針對(duì)實(shí)現(xiàn)編程