用JavaScript实现的设计模式之commandline(命令行)模式

简介: 用JavaScript实现的设计模式之commandline(命令行)模式

使用Commandline设计模式之前的源代码:

<html>
<script>
// Priority: ActiveX > HTML5 > Flash > Form(default)
function isActiveXSupported(){
  //...
  return false;
}
function isHTML5Supported(){
  //...
  return false;
}
function isFlashSupported(){
  //...
  return false;
}
var uploadAPI;
if ( isActiveXSupported()) {
  // lots of initialization work
  uploadAPI = { "name": "ActiveX"};
}
else if( isHTML5Supported()) {
  // lots of initialization work
  uploadAPI = { "name": "HTML5"};
}
else if( isFlashSupported()) {
  // lots of initialization work
  uploadAPI = { "name": "Flash"};
}
else {
  // lots of initialization work
  uploadAPI = { "name": "Form"};
}
console.log(uploadAPI);
</script>
</html>

我们可以使用CommandLine设计模式,将这些冗长的IF-ELSE语句消除:

image.png

commandline命令行模式的JavaScript实现版本:

<html>
<script>
Function.prototype.after = function( func ){
    var _self = this;
    return function() {
       var ret = _self.apply( this, arguments );
       if ( ret  ) {
          return ret;
       }
       return func.apply( this, arguments);
    }
}
// Priority: ActiveX > HTML5 > Flash > Form(default)
var getActiveX = function() {
  try {
    // lots of initialization work
    a();
    return { "name": "ActiveX"};
  }
  catch (e) {
    // user broswer does not support ActiveX
    return null;
  }
}
var getHTML5 = function() {
  try {
    // lots of initialization work
    return { "name": "HTML5"};
  }
  catch (e) {
    // user broswer does not support HTML5
    return null;
  }
}
var getFlash = function() {
  try {
    // lots of initialization work
    return { "name": "Flash"};
  }
  catch (e) {
    // user broswer does not support Flash
    return null;
  }
}
var getForm = function() {
  return { "name": "Form"};
}
var uploadAPI = getActiveX.after(getHTML5).after(getFlash).after(getForm)();
console.log(uploadAPI);
</script>
</html>
相关文章
|
25天前
|
设计模式 JavaScript 前端开发
js设计模式【详解】—— 职责链模式
js设计模式【详解】—— 职责链模式
31 8
|
25天前
|
设计模式 JavaScript 前端开发
js设计模式【详解】—— 组合模式
js设计模式【详解】—— 组合模式
29 7
|
7天前
|
设计模式 算法 Java
跟着GPT学设计模式之模板模式
模板模式是一种行为型设计模式,它定义了一个操作中的算法骨架,将一些步骤的具体实现延迟到子类中。该模式使得子类可以在不改变算法结构的情况下,重新定义算法中的某些步骤。
26 6
|
17天前
|
设计模式 Go
Go语言设计模式:使用Option模式简化类的初始化
在Go语言中,面对构造函数参数过多导致的复杂性问题,可以采用Option模式。Option模式通过函数选项提供灵活的配置,增强了构造函数的可读性和可扩展性。以`Foo`为例,通过定义如`WithName`、`WithAge`、`WithDB`等设置器函数,调用者可以选择性地传递所需参数,避免了记忆参数顺序和类型。这种模式提升了代码的维护性和灵活性,特别是在处理多配置场景时。
47 8
|
25天前
|
设计模式 JavaScript Go
js设计模式【详解】—— 状态模式
js设计模式【详解】—— 状态模式
31 7
|
25天前
|
设计模式 JavaScript
js设计模式【详解】—— 桥接模式
js设计模式【详解】—— 桥接模式
33 6
|
25天前
|
设计模式 JavaScript
js设计模式【详解】—— 原型模式
js设计模式【详解】—— 原型模式
24 6
|
25天前
|
设计模式 JavaScript 算法
js设计模式【详解】—— 模板方法模式
js设计模式【详解】—— 模板方法模式
28 6
|
25天前
|
设计模式 存储 JavaScript
js设计模式【详解】—— 享元模式
js设计模式【详解】—— 享元模式
28 6
|
25天前
|
设计模式 JavaScript API
js设计模式【详解】—— 命令模式
js设计模式【详解】—— 命令模式
24 6