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