定義:
命令模式:將請(qǐng)求封裝成對(duì)象,這可以讓你使用不同的請(qǐng)求、隊(duì)列,或者日志請(qǐng)求來(lái)參數(shù)化其他對(duì)象。命令模式也可以支持撤銷操作。
命令模式在Java的框架中使用非常頻繁,比如最近我研究的一個(gè)Java的架構(gòu)基礎(chǔ)框架COLA,里面就使用了命令模式來(lái)處理業(yè)務(wù)請(qǐng)求;
代碼:
// 命令接口
interface ICommand {
execute(): void
}
// 增加用戶命令
class AddUserCommand implements ICommand {
constructor(public name: string) {
this.name = name
}
public execute() {
console.log('add user:' + this.name)
}
}
// 刪除用戶命令
class DeleteUserCommand implements ICommand {
constructor(public id: number) {
this.id = id
}
public execute() {
console.log('delete user by id:' + this.id)
}
}
// 命令執(zhí)行者,這里可以設(shè)置一個(gè)線程池來(lái)調(diào)度
class CommandHub {
public send(cmd: ICommand) {
cmd.execute()
}
}
const commandHub = new CommandHub()
// 發(fā)送添加用戶命令
const addUserCommand = new AddUserCommand('mimi')
commandHub.send(addUserCommand)
// 發(fā)送刪除用戶命令
const deleteUserCommand = new DeleteUserCommand(99)
commandHub.send(deleteUserCommand)
如果需要實(shí)現(xiàn)撤銷命令,實(shí)現(xiàn)如下
// 命令接口
interface ICommand {
execute(): void
// 撤銷方法
undo(): void
}
在實(shí)現(xiàn)類里,加入撤銷該操作的邏輯,然后每個(gè)命令都發(fā)到一個(gè)隊(duì)列里,CommandHub不斷從隊(duì)列里取出命令執(zhí)行execute方法,執(zhí)行完了再放到歷史命令隊(duì)列里,當(dāng)撤銷操作的時(shí)候,從歷史命令隊(duì)列里取出命令,執(zhí)行redo方法;