前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >用JavaScript实现的设计模式之commandline(命令行)模式

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

作者头像
Jerry Wang
发布2020-03-19 17:28:41
4000
发布2020-03-19 17:28:41
举报

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

代码语言:javascript
复制
<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语句消除:

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

代码语言: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>
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-03-18 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档