JavaScript命令模式原理与用法实例详解

作者:WFaceBoss 时间:2024-04-23 09:32:04 

本文实例讲述了JavaScript命令模式原理与用法。分享给大家供大家参考,具体如下:

第一,命令模式:
(1)用于消除调用者和接收者之间直接的耦合的模式,并且可以对(调用这个过程进行留痕操作)

(2)真的不要乱用这个模式,以为他使你简单调用写法变得非常的复杂和有些难以理解。

(3)你的业务出现了 (回退操作)(重做操作)的需求的时候你就要考虑使用这个模式了。
命令的原理:
JavaScript命令模式原理与用法实例详解

一种情况为发出者直接作用于执行者,这样耦合度很高,另外一种情况为,在发出者和执行者之间增加一个用存储命令的命令访问库也即命令命令模式。

第二,现在我们通过一个需求来学习该模式
需求为:

1.有一个"添加流程的按钮"单击的时候 就会添加一个新的文本当做流程的描述

2.有"返回","重做" 2个按钮来完成相应的任务。
第三,界面为


<body>
<input type="text" id="flow">
<input type="button" value="添加新流程" onclick="API.addFlow()">
<br>
<input type="button" value="ctrl+z回退" onclick="API.ret()">
<input type="button" value="ctrl+z+x重做" onclick="API.again()">
<div id= "div01"></div>

<script src="Js/设计模式第三部分/命令模式/keymaster.min.js"></script>
<script src="Js/设计模式第三部分/命令模式/uuid.js"></script>
<script src="Js/设计模式第三部分/命令模式/(18)命令模式.js"></script>
</body>

  效果为,JavaScript命令模式原理与用法实例详解


根据上述图我们逐步完成
步骤一,定义主应用程序----接收者


function manager() {
       this.addFlow=function (id,value) {
           //1.得到目标节点
         var div=document.getElementById("div01");
         var newFlow=document.createElement("div");
         newFlow.setAttribute("id",id);
         newFlow.innerHTML=value;
         div.appendChild(newFlow);

}
   }

 步骤二,为对象(执行者)建立命令访问库 ---意思是可以通过extcute方法访问到addFlow方法


manager.prototype.extcute=(function () {
     /*command 命令对象
     * */
     return function (command) {
       return this[command.method](command.id,command.value);
     }

})();

步骤三,初始化主类


var ma = new manager();//可以用该对象,调用其的东西
     //用于存储"调用对象命令的"集合
     var commands = new Array();
     //集合的游标--初始化在末尾
     var index = commands.length;

步骤四,客户端----发出者


var API=function () {
  this.addFlow=function () {
    //把调用封装起来
    var command={
      method:"addFlow",
      id:new UUID().createUUID(),//产生id的插件
      value:document.getElementById("flow").value
    };
    //把调用对象保存起来,用于回退和重做作用
    commands.push(command);
    //重新定位游标---赋值记录
    index = commands.length;
    //调用
    ma.extcute(command);
  };
  /**
   * 用于返回的方法
   */
  this.ret=function () {
    if(index-1<0){
      alert("已经到了最后一步了...");
    }else {
      var all=document.getElementById("div01").childNodes;
      document.getElementById("div01").removeChild(all[all.length-1]);
      index=index-1;
    }
  };
  /**
   * 用于重做的方法
   */
  this.again=function () {
    if(index>=commands.length){
      alert("已经到了最前面一步了,不能进行重做...");
    }else {
      var command=commands[index];//获取当前的命令位置
      ma.extcute(command);
      index=index+1;
    }
  }
}

步骤五,实例化客户端


API=new API();//实例化

这样html中的事件就可以起作用了。

在这里我们使用插件来让其功能支持自定义的键盘事件,插件名称为:keymaster.js

首先,如html中一样引入文件,

然后值调用key添加自定义的键盘事件


//添加支持ctrl+z--返回
key("ctrl+z",function () {

API.ret();
});
//重做---
key("ctrl+shift+x",function () {
 API.again();

})

为此我们可以使用键盘的指定组合实现和鼠标点击一样的效果。

这里需要说明一下客户端的API中的id值,也是通过插件来动态生成的------插件名称为:uuid.js。这里附上源码


/*

uuid.js - Version 0.2
JavaScript Class to create a UUID like identifier

Copyright (C) 2006-2008, Erik Giberti (AF-Design), All rights reserved.

This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place, Suite 330, Boston, MA 02111-1307 USA

The latest version of this file can be downloaded from
http://www.af-design.com/resources/javascript_uuid.php

HISTORY:
6/5/06   - Initial Release
5/22/08 - Updated code to run faster, removed randrange(min,max) in favor of
    a simpler rand(max) function. Reduced overhead by using getTime()
    method of date class (suggestion by James Hall).

KNOWN ISSUES:
- Still no way to get MAC address in JavaScript
- Research into other versions of UUID show promising possibilities
(more research needed)
- Documentation needs improvement

*/

// On creation of a UUID object, set it's initial value
function UUID(){
 this.id = this.createUUID();
}

// When asked what this Object is, lie and return it's value
UUID.prototype.valueOf = function(){ return this.id; }
UUID.prototype.toString = function(){ return this.id; }

//
// INSTANCE SPECIFIC METHODS
//

UUID.prototype.createUUID = function(){
 //
 // Loose interpretation of the specification DCE 1.1: Remote Procedure Call
 // described at http://www.opengroup.org/onlinepubs/009629399/apdxa.htm#tagtcjh_37
 // since JavaScript doesn't allow access to internal systems, the last 48 bits
 // of the node section is made up using a series of random numbers (6 octets long).
 //
 var dg = new Date(1582, 10, 15, 0, 0, 0, 0);
 var dc = new Date();
 var t = dc.getTime() - dg.getTime();
 var h = '-';
 var tl = UUID.getIntegerBits(t,0,31);
 var tm = UUID.getIntegerBits(t,32,47);
 var thv = UUID.getIntegerBits(t,48,59) + '1'; // version 1, security version is 2
 var csar = UUID.getIntegerBits(UUID.rand(4095),0,7);
 var csl = UUID.getIntegerBits(UUID.rand(4095),0,7);

// since detection of anything about the machine/browser is far to buggy,
 // include some more random numbers here
 // if NIC or an IP can be obtained reliably, that should be put in
 // here instead.
 var n = UUID.getIntegerBits(UUID.rand(8191),0,7) +
     UUID.getIntegerBits(UUID.rand(8191),8,15) +
     UUID.getIntegerBits(UUID.rand(8191),0,7) +
     UUID.getIntegerBits(UUID.rand(8191),8,15) +
     UUID.getIntegerBits(UUID.rand(8191),0,15); // this last number is two octets long
 return tl + h + tm + h + thv + h + csar + csl + h + n;
}

//
// GENERAL METHODS (Not instance specific)
//

// Pull out only certain bits from a very large integer, used to get the time
// code information for the first part of a UUID. Will return zero's if there
// aren't enough bits to shift where it needs to.
UUID.getIntegerBits = function(val,start,end){
 var base16 = UUID.returnBase(val,16);
 var quadArray = new Array();
 var quadString = '';
 var i = 0;
 for(i=0;i<base16.length;i++){
   quadArray.push(base16.substring(i,i+1));  
 }
 for(i=Math.floor(start/4);i<=Math.floor(end/4);i++){
   if(!quadArray[i] || quadArray[i] == '') quadString += '0';
   else quadString += quadArray[i];
 }
 return quadString;
}

// Numeric Base Conversion algorithm from irt.org
// In base 16: 0=0, 5=5, 10=A, 15=F
UUID.returnBase = function(number, base){
 //
 // Copyright 1996-2006 irt.org, All Rights Reserved.  
 //
 // Downloaded from: http://www.irt.org/script/146.htm  
 // modified to work in this class by Erik Giberti
 var convert = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
 if (number < base) var output = convert[number];
 else {
   var MSD = '' + Math.floor(number / base);
   var * = number - MSD*base;
   if (MSD >= base) var output = this.returnBase(MSD,base) + convert[ * ];
   else var output = convert[MSD] + convert[ * ];
 }
 return output;
}

// pick a random number within a range of numbers
// int b rand(int a); where 0 <= b <= a
UUID.rand = function(max){
 return Math.floor(Math.random() * max);
}

// end of UUID class file

希望本文所述对大家JavaScript程序设计有所帮助。

来源:https://www.cnblogs.com/wfaceboss/p/7703873.html

标签:JavaScript,命令模式
0
投稿

猜你喜欢

  • 让ASP组件来保护你的网站,自定义加密方法的使用

    2009-11-07 19:27:00
  • ASP控制每页打印行数实例

    2008-04-13 06:48:00
  • Python 多线程Threading初学教程

    2022-12-17 18:53:43
  • 6G数据库的导入 报各种错误的解决办法

    2024-01-28 09:58:22
  • Python Opencv图像处理基本操作代码详解

    2023-06-08 08:08:05
  • python 3.6.5 安装配置方法图文教程

    2021-05-17 01:00:19
  • 基于python分享极坐标下的几类典型曲线

    2023-05-02 18:18:37
  • Oracle 正则表达式实例详解

    2024-01-25 23:43:01
  • python 如何使用find和find_all爬虫、找文本的实现

    2023-09-30 02:01:46
  • XML教程 WEB页面工具语言XML的定义

    2008-05-29 10:54:00
  • 详解Python不同版本之间的切换方法

    2023-12-28 05:22:06
  • Python3基础之输入和输出实例分析

    2022-08-05 11:08:09
  • uniapp路由uni-simple-router实例详解

    2023-09-24 21:27:04
  • python用BeautifulSoup库简单爬虫实例分析

    2022-04-02 21:42:00
  • Request.ServerVariables应用实例

    2008-03-11 11:57:00
  • Python闭包的两个注意事项(推荐)

    2023-11-29 14:01:09
  • 基于Git的常用撤销技巧与解决冲突方法(推荐)

    2023-07-01 19:20:28
  • python 实现视频流下载保存MP4的方法

    2021-09-13 06:31:38
  • 如何使用PHP计算上一个月的今天

    2023-11-15 14:16:25
  • 利用Python实现K-Means聚类的方法实例(案例:用户分类)

    2023-05-15 13:14:34
  • asp之家 网络编程 m.aspxhome.com