zoukankan      html  css  js  c++  java
  • 《JavaScript设计模式与开发实践》读书笔记之命令模式

    1.命令模式

    1.1 传统的命令模式

    命令模式的应用场景:请求的发送者和请求接收者消除彼此耦合关系

    以页面点击按钮为例

    点击按钮后,借助命令对象,解开按钮和负责具体行为对象之间的耦合

    <body>
        <button id='button1'>按钮1</button>
        <button id='button2'>按钮2</button>
        <button id='button3'>按钮3</button>
    </body>
    
    <script>
        var button1=document.getElementById('button1');
        var button2=document.getElementById('button2');
        var button3=document.getElementById('button3');    
    </script>

    定义setCommand函数,绑定行为。

    var setCommand=function(button,command){
        button.onclick=function(){
            command.execute();
        }
    }

    最后编写具体的行为,这些行为完成菜单栏的几项功能

    var MenuBar={
        refresh:function(){
            console.log('refresh');
        }
    };
    
    var SubMenu={
        add:function(){
            console.log('add');
        },
        del:function(){
            console.log('del');
        }
    };

    把行为封装在命令类中

    var RefreshMenuBarCommand=function(receiver){
        this.receiver=receiver;
    };
    RefreshMenuBarCommand.prototype.execute=function(){
        this.receiver.refresh();
    };
    
    var AddSubMenuCommand=function(receiver){
        this.receiver=receiver;
    };
    AddSubMenuCommand.prototype.execute=function(){
        this.receiver.add();
    };
    
    var DelSubMenuCommand=function(receiver){
        this.receiver=receiver;
    };
    DelSubMenuCommand.prototype.execute=function{
        this.receiver.del();
    }

    最后将命令接收者传入到command对象中,并且将command对象绑定到button上

    var refreshMenuBarCommand=new RefreshMenuBarCommand(MenuBar);
    var addSubMenuCommand=new AddSubMenuCommand(SubMenu);
    var delSubMenuCommand=new DelSubMenuCommand(SubMenu);
    setCommand(button1,refreshMenuBarCommand);
    setCommand(button2,addSubMenuCommand);
    setCommand(button3,delSubMenuCommand);

    1.2 JavaScript这的命令模式 

    var bindClick=function(button,func){
        button.onclick=func;
    };
    var MenuBar={
        refresh:function(){
            console.log('refresh');
        }
    };
    
    var SubMenu={
        add:function(){
            console.log('add');
        },
        del:function(){
            console.log('del');
        }
    };
    bindClick(button1,MenuBar.refresh);
    bindClick(button2,SubMenu.add);
    bindClick(button3,SubMenu.del);
  • 相关阅读:
    为什么多线程读写 shared_ptr 要加锁?
    iOS开发那些事iOS6 UI状态保持和恢复
    Hook钩子程序(续)
    JavaScript 项目构建工具 Grunt 实践:任务和指令
    浏览器插件之ActiveX开发(五)
    mongodb副本集架构搭建
    Hadoop 0.23.3版本
    Grails 中使用 grailseventspush 实现 ajax/comet/websocket 消息推送
    razor中@相对于<% %>的优势
    Chrome developer tool介绍(javascript调试)
  • 原文地址:https://www.cnblogs.com/GongQi/p/4652810.html
Copyright © 2011-2022 走看看