Home  >  Article  >  php教程  >  星际争霸之php状态模式

星际争霸之php状态模式

WBOY
WBOYOriginal
2016-06-07 17:23:021265browse

星际的一些兵种会有不止一种状态,比如坦克可以架起来,机枪兵可以打兴奋剂,甚至还有一些被动的,比如被虫族女王喷洒绿色液体后,敌人的行动变慢。

如果按照一般的思路,每次我们对一个小兵进行操作的时候,比如一辆坦克,我们都要用if判断他的状态,这样代码中会有很多的if,else或者swith。

不过我们可以发现,我们需要的是他在某个状态下的行为,如果把这些行为按照状态封装起来,就可以减少大量的判断。

待解决的问题:封装坦克的状态,让状态自己去控制行为。

思路:把状态作为属性,兵种类本身只控制状态的变化,具体的行为由状态类定义。

状态(State)模式示例:

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn