命令模式
命令模式是一种数据驱动的设计模式,它属于行为模式,请求以命令的形式包裹在对象中,并传给调用对象,调用对象寻找处理该命令合适的对象,并把该命令传给相应的对象,该对象执行命令.
三种角色
- Receiver接受者角色:该角色就是干活角色,命令传递到这里是应该被执行的.
- Command命令角色:需要执行的所有命令都在这里声明.
- Invoker调用者角色:接收到命令,并执行命令.
-
图例
代码示例
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() //烹饪
- 应用场景
1.计数器
<!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>
-
效果
优点 | 缺点 |
---|---|
降低了系统的耦合度,新的命令容易添加到系统中. | 使用命令模式导致系统中有过多的具体命令类. |