欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2024-01-07 21:19:10
...

使用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语句消除:

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

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>

上一篇:

下一篇: