命令模式
命令模式是一種數(shù)據(jù)驅(qū)動(dòng)的設(shè)計(jì)模式,它屬于行為模式,請(qǐng)求以命令的形式包裹在對(duì)象中,并傳給調(diào)用對(duì)象,調(diào)用對(duì)象尋找處理該命令合適的對(duì)象柏副,并把該命令傳給相應(yīng)的對(duì)象,該對(duì)象執(zhí)行命令.
三種角色
- Receiver接受者角色:該角色就是干活角色,命令傳遞到這里是應(yīng)該被執(zhí)行的.
- Command命令角色:需要執(zhí)行的所有命令都在這里聲明.
- Invoker調(diào)用者角色:接收到命令检盼,并執(zhí)行命令.
-
圖例
image.png 代碼示例
class Cooker{
cook(){
return console.log('烹飪')
}
}
class Cleaner{
clean(){
return console.log('清潔')
}
}
class CookCommand{
constructor(receiver){
this.receiver=receiver
}
execute(){
this.receiver.cook()
}
}
class CleanCommand{
constructor(receiver){
this.receiver=receiver
}
execute(){
this.receiver.clean()
}
}
class Customer{
constructor(command){
this.command=command
}
clean(){
this.command.execute()
}
cook(){
this.command.execute()
}
}
let cooker=new Cooker()
let cleaner=new Cleaner()
let cookCommand=new CookCommand(cooker)
let customer=new Customer(cookCommand);
customer.cook() //烹飪
- 應(yīng)用場景
1.計(jì)數(shù)器
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<p id="number">0</p>
<button id="addBtn">+</button>
<button id="revocation">撤回</button>
<script>
let number=document.getElementById('number')
let worker={
oldVal:0,
add(){
let oldVal=isNaN(number.innerHTML) ? 0:parseInt(number.innerHTML)
worker.oldVal=oldVal
number.innerHTML=oldVal+1
},
revocation(){
number.innerHTML=worker.oldVal
}
}
class AddCommand{
constructor(receiver){
this.receiver=receiver
}
execute(){
this.receiver.add()
}
}
class RevocationCommand{
constructor(receiver){
this.receiver=receiver
}
execute(){
this.receiver.revocation()
}
}
let addCommand=new AddCommand(worker)
let revocationCommand=new RevocationCommand(worker)
document.getElementById('addBtn').addEventListener('click',()=>addCommand.execute())
document.getElementById('revocation').addEventListener('click',()=>revocationCommand.execute())
</script>
</body>
</html>
-
效果
image.png
優(yōu)點(diǎn) | 缺點(diǎn) |
---|---|
降低了系統(tǒng)的耦合度,新的命令容易添加到系統(tǒng)中. | 使用命令模式導(dǎo)致系統(tǒng)中有過多的具體命令類. |