状态模式:当一个对象的内部状态发生变化时,会导致其行为的改变,这看起来是改变了对象。
1、代码实现
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head>
<meta charset="utf-8">
<style>
div {
margin-top: 5px;
border:solid 1px blue;
padding: 5px;
}
</style>
</head>
<body>
<script type="text/javascript">
var ResultState = function(){
var States = {
state0:function(){
console.log("这是第一种情况");
},
state1:function(){
console.log("这是第二种情况");
},
state2:function(){
console.log("这是第三种情况");
}
}
function show(result){
States['state'+result] && States['state'+result]();
}
return {
show:show
}
}();
//使用
ResultState.show(2); //输出:这是第三种情况
</script>
</body>
</html>