JS设计模式-命令模式

2022/2/6 23:12:46

本文主要是介绍JS设计模式-命令模式,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

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>

通过闭包的形式实现



这篇关于JS设计模式-命令模式的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程