化繁为简的状态模式

Table of Contents

最近看了同事写的一块代码,逻辑非常复杂,我们讨论了实现的方式,我建议他改用状态模式, 这样可以省去很多复杂的判断分支

这是用状态模式的做法

file

不用状态模式的代码大致如此

if(cpuRatio < xxx && memRatio < xxx) {
     state=Normal
} else if(cpuRatio > xxx && memRatio > xxx) {
     state=Busy
}
else if(cpuRatio > xxx && memRatio > xxx) {
     state=Crazy
}

if(state == Crazy) {
     delegateOtherDoSomething()
} else if (state == Busy) {
     complainAndDoSomething()
} else if (state == Normal) {
     doSomething()
} else {
     doSomething();
}

而用状态模式的代码大致如此

newState = currentState.checkState();
newState.doSomething();

当然我省略了 checkState 的逻辑,该做的事其实并没有少多少,但是看起来清楚多了。

Comments |0|

Legend *) Required fields are marked
**) You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>
Category: Uncategorized