js 状态模式

状态模式:解决多个分支判断时代码臃肿问题,以及状态间的耦合,便于增删改查。

var rewards=['奖品1','奖品2','奖品3','奖品4','奖品5','奖品6'];
var touzi=(function () {
var result=Math.floor(Math.random()*6+1);
return{
res:result
}
})();
(function (endRes) {
if (endRes===1){
console.log('您获得了'+rewards[0]);
}else if(endRes===2){
console.log('您获得了'+rewards[1]);
}else if(endRes===3){
console.log('您获得了'+rewards[2]);
}else if(endRes===4){
console.log('您获得了'+rewards[3]);
}else if(endRes===5){
console.log('您获得了'+rewards[4]);
}else if(endRes===6){
console.log('您获得了'+rewards[5]);
}
})(touzi.res)


更清爽的
var State=function () {
var States={
state0:function (i) {
alert('state0')
},
state1:function (i) {
alert('state1')
},
state2:function (i) {
alert('state2')
},
state3:function (i) {
alert('state3')
}
};
function getRes(res) {
States['state'+res] && States['state'+res]();
}
return{
setState:getRes
}
}();
State.setState(0)

log函数监控操作
var log=(function () {
var info="";
return{
set:function (msg) {
info+=msg+"\n"
},
getAll:function () {
console.log(info);
info=""
}
}
})();

var ThingState=function () {
var _needState={};
states={
state0:function () {
log.set('state0 -> 一等奖')
},
state1:function () {
log.set('state1 -> 二等奖');
},
state2:function () {
log.set("state2 -> 三等奖");
}
};
var Action={
addStates:function () {
var arg=arguments;
_needState={};
if(arg.length){
for(var i=0,l=arg.length;i<l;i++){
_needState[arg[i]]=true
}
}
return this;
},
mission:function () {
for(key in _needState){
states[key] && states[key]();
}
return this
}
};
return{
addStates:Action.addStates,
mission:Action.mission
}
};

var mac=new ThingState();
mac.addStates('state0','state1')
.mission()
.addStates('state2')
.mission();
log.getAll();
posted @ 2017-12-25 10:56  redn  阅读(635)  评论(0编辑  收藏  举报