定义
定义一系列的算法,把它们一个个封装起来,并且使它们可以相互替换。
实现
思路:创建表示各种策略的对象,和一个行为随着策略对象改变而改变的 context 对象。
一个简单的加减乘例子:
interface Compute<T> {
computeF (num1: T, num2: T): T
}
// 创建策略对象
class ComputeAdd implements Compute<number> {
public computeF (
num1: number,
num2: number
): number {
return num1 + num2
}
}
class ComputeSub implements Compute<number> {
public computeF (
num1: number,
num2: number
): number {
return num1 - num2
}
}
class ComputeMul implements Compute<String> {
public computeF (
num1: String,
num2: String
): String {
return `${num1} + ${num2}`
}
}
// 创建行为类
class Context {
public compute: Compute<any>
public constructor (compute: Compute<any>) {
this.compute = compute
}
public excuteCompute (
num1: number,
num2: number
): number {
return this.compute.computeF(num1, num2)
}
}
let context1 = new Context(new ComputeAdd())
.excuteCompute(1, 2)
let context2 = new Context(new ComputeSub())
.excuteCompute(1, 2)
let content3 = new Context(new ComputeMul())
.excuteCompute(1, 2)
console.log(context1, context2, content3) // 3, -1, 1 + 2
复杂一点的例子(打怪):
// 武器接口
interface Weapon {
useWeapon (): void
}
// 技能接口
interface Skill {
useSkill (): void
}
// 武器类
class Gun implements Weapon {
public useWeapon () {
console.log( 'Weapon: Gun')
}
}
class Stick implements Weapon {
public useWeapon () {
console.log('Weapon: Stick')
}
}
// 技能类
class Magic implements Skill {
public useSkill () {
console.log('Skill: Magic')
}
}
class Kongfu implements Skill {
public useSkill () {
console.log('Skill: Chinese Kongfu')
}
}
// 抽象类,用于给其他类继承
abstract class Way {
// 武器
public weapon: Weapon
// 技能
public skill: Skill
// 设置武器
public setWeapon (weapon: Weapon): void {
this.weapon = weapon
}
// 设置技能
public setSkill (skill: Skill): void {
this.skill = skill
}
public getWeaponAndSkill (): void {
this.weapon.useWeapon()
this.skill.useSkill()
}
// 抽象方法
public abstract saySome (): void
}
class SimpleWay extends Way {
public constructor () {
super()
this.weapon = new Gun()
this.skill = new Magic()
}
public saySome () {
console.log('屠龙宝刀,点击就送')
}
}
const way = new SimpleWay()
way.saySome()
console.log('=======')
way.getWeaponAndSkill()
console.log('=======')
way.setWeapon(new Stick)
way.setSkill(new Kongfu)
way.getWeaponAndSkill()
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。