JS设计模式-命令模式
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>
<button id = 'button1'>button1</button>
<button id = 'button2'>button1</button>
<button id = 'button3'>button1</button>
</body>
<script>
var mainMenu = {
refreshMainMenu:function(){
console.log("refreshMainMenu");
}
}
var subMenu = {
addItem:function(){
console.log('addItem')
},
delItem:function(){
console.log('delItem');
}
}
function setCommand(button,command){
button.onclick = function(){
command.execute()
}
}
function RefreshMainMenu(receiver){
this.receiver = receiver
}
RefreshMainMenu.prototype.execute = function(){
this.receiver.refreshMainMenu()
}
function AddItem(receiver){
this.receiver = receiver
}
AddItem.prototype.execute = function(){
this.receiver.addItem()
}
function DelItem(receiver){
this.receiver = receiver
}
DelItem.prototype.execute = function(){
this.receiver.delItem()
}
var refresh = new RefreshMainMenu(mainMenu)
var add = new AddItem(subMenu)
var del = new DelItem(subMenu)
setCommand(button1,refresh)
setCommand(button2,add)
setCommand(button3,del)
</script>
</html>
通过统一的接口execute来执行命令
2.其他模式
<!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>
<button id = 'button1'>button1</button>
<button id = 'button2'>button1</button>
<button id = 'button3'>button1</button>
</body>
<script>
var mainMenu = {
refreshMainMenu:function(){
console.log("refreshMainMenu");
}
}
var subMenu = {
addItem:function(){
console.log('addItem')
},
delItem:function(){
console.log('delItem');
}
}
function setCommand(button,command){
button.onclick = function(){
command.execute()
}
}
function RefreshMainMenu(receiver){
return {
execute:function(){
receiver.refreshMainMenu()
}
}
}
function AddItem(receiver){
return {
execute:function(){
receiver.addItem()
}
}
}
function DelItem(receiver){
return {
execute:function(){
receiver.delItem()
}
}
}
var refresh = RefreshMainMenu(mainMenu)
var add = AddItem(subMenu)
var del = DelItem(subMenu)
setCommand(button1,refresh)
setCommand(button2,add)
setCommand(button3,del)
</script>
</html>
通过闭包的形式实现