20 状态模式

原文转载:https://blog.csdn.net/sinat_21107433/article/details/102966121

在软件系统中,有些对象在不同的条件下也具有不同的状态,不同状态之间可以相互转换。通过判断不同的条件分支(if...else...或者switch..case...)可以进行状态的转换。但这样势必使得代码的判断逻辑变得复杂,降低系统的可维护性。如果新加入一种状态,还需要修改判断逻辑,不符合开闭原则。

为解决复杂对象的多种状态转换问题,并使客户端代码与对象状态之间的耦合度降低,可以使用状态模式

1.状态模式简介

状态模式将一个对象的状态从对象中分离出来,封装到专门的状态类中,使得对象状态可以灵活变化。对于客户端而言,无需关心对象转态的转换以及对象所处的当前状态,无论处于何种状态的对象,客户端都可以一致处理。

状态模式:

允许一个对象在其内部状态改变时改变它的行为。对象看起来似乎修改了它的类。

2.状态模式结构

状态模式的UML图如下。

状态模式引入了抽象层,具有抽象状态类和具体状态类,还包括一个上下文境类:

  • Context(上下文类):是拥有多种状态的对象。上下文类的状态存在多样性,并且在不同的状态下,对象表现出不同的行为。在上下文类中,维护了一个抽象状态类的实例。
  • State(抽象状态类):声明了一个接口,用于封装与在上下文类中的一个特定状态相关的行为,在子类中实现在各种不同状态对应的方法。不同的子类可能存在不同的实现方法,相同的方法可以写在抽象状态类中。
  • ConcreteState(具体状态类):实现具体状态下的方法,每一个具体状态类对应一个具体的状态。

值得注意的是,上下文中维护了一个状态类的指针或者引用,可以由上下文类来觉得具体实例化为哪一个具体的状态对象,也可以由具体的状态类来决定转换为哪一个实例,所以,上下文类和状态类之间存在依赖甚至相互引用的关系

 
  1. // 1.由环境类来决定实例化为哪一个具体状态类对象

  2. class Context

  3. {

  4. public:

  5. void convertState(){

  6. if (condition1){

  7. this->state = new ConcreteStateA();

  8. }

  9. else if (condition2){

  10. this->state = new ConcreteStateB();

  11. }

  12. else{

  13. // do something

  14. }

  15. }

  16. private:

  17. // 引用状态对象

  18. State *state;

  19. };

  20. // 2.有具体状态类来决定转换成哪一个具体状态类对象

  21. class ConcreteState :public State

  22. {

  23. public:

  24. void convertState(Context* ctx){

  25. if (condition1){

  26. ctx->setState(new ConcreteStateA());

  27. }

  28. else if (condition2){

  29. ctx->setState(new ConcreteStateB());

  30. }

  31. else{

  32. // do something

  33. }

  34. }

  35. };

下面是状态模式的典型用法:

 
  1. #ifndef __DEMO_H__

  2. #define __DEMO_H__

  3.  
  4. // 抽象状态类

  5. class State

  6. {

  7. public:

  8. // 声明抽象方法

  9. virtual void handle() = 0;

  10. };

  11.  
  12. // 具体状态类

  13. class ConcreteState :public State

  14. {

  15. public:

  16. // 实现

  17. void handle(){

  18. // ……

  19. }

  20. };

  21.  
  22. // 上下文类

  23. class Context

  24. {

  25. public:

  26. // set方法设置状态对象

  27. void setState(State* iState){

  28. this->state = iState;

  29. }

  30. // 对外封装的方法

  31. void request(){

  32. // do something

  33. state->handle();

  34. }

  35. private:

  36. // 引用状态对象

  37. State *state;

  38. };

  39.  
  40. #endif //__DEMO_H__

3.状态模式代码实例

接下来Jungle用一个实例来应用状态模式。

在某纸牌游戏中,游戏人物分为入门级(primary)熟练级(Secondary)高手级(Professional)骨灰级(Final)四种级别,由人物的积分来划分角色等级,游戏胜利将增加积分,失败将扣除积分。入门级有最基本的游戏功能play(),熟练级增加了游戏胜利积分加倍功能doubleScore(),高手级在熟练级的基础上增加了换牌功能changeCards(),骨灰级在高手级的基础上再增加了偷看他人纸牌的功能peekCards()

积分规则如下:

基础分:100,游戏胜利+50分,游戏失败+30分;

入门级:0~150;熟练级150~200;高手级:200~250;骨灰级:250以上

本例设计游戏账户GameAccount为上下文类,维护了一个级别类(Level)的对象实例。GameAccount中定义了一个代表积分的score整型和统一封装的方法playcard(),在该方法中再调用具体级别的各个技能方法。采用随机数的方式来随机判定牌局的输赢,以增减积分。

级别类Level为抽象类,声明了play()、doubleScore()、changeCards()、seekCards()的抽象方法,在四个具体级别类Primary、Secondary、Professional和Final类中具体实现了该方法,具体来说是根据该级别是否有权利使用该技能来打印一行话。upgradeLevel()方法用于判断每局牌结束后该游戏账户的积分是否可以升级或者降级,通过setLevel()方法改变当前账户的游戏级别

该实例的UML图如下:

3.1.上下文类:游戏账户类

 
  1. //头文件

  2. #ifndef __GAMEACCOUNT_H__

  3. #define __GAMEACCOUNT_H__

  4.  
  5. using namespace std;

  6. #include <iostream>

  7. // 前向声明

  8. class Level;

  9.  
  10. class GameAccount

  11. {

  12. public:

  13. GameAccount();

  14. GameAccount(string iName);

  15. string getName();

  16. void win();

  17. void lose();

  18. void playCard();

  19. void setLevel(Level*);

  20. int getScore();

  21. void setScore(int);

  22.  
  23. private:

  24. Level* level;

  25. int score;

  26. string name;

  27. };

  28.  
  29. #endif

  30.  
  31. //源文件

  32. #include "GameAccount.h"

  33. #include "Level.h"

  34. #include <Windows.h>

  35. #include <time.h>

  36. #define random(x) (rand()%x)

  37.  
  38. GameAccount::GameAccount(){

  39. printf("创立游戏角色,积分:100,级别:PRIMARY\n");

  40. score = 100;

  41. name = "none";

  42. setLevel(new Primary(this));

  43. }

  44.  
  45. GameAccount::GameAccount(string iName){

  46. printf("创立游戏角色,积分:100,级别:PRIMARY\n");

  47. score = 100;

  48. name = iName;

  49. setLevel(new Primary(this));

  50. }

  51.  
  52. void GameAccount::setLevel(Level* iLevel){

  53. this->level = iLevel;

  54. }

  55.  
  56. string GameAccount::getName(){

  57. return name;

  58. }

  59.  
  60. void GameAccount::playCard(){

  61. this->level->playCard();

  62.  
  63. Sleep(100);

  64. srand((int)time(0));

  65. int res = random(2);

  66. if (res % 2 == 0){

  67. this->win();

  68. }

  69. else{

  70. this->lose();

  71. }

  72.  
  73. this->level->upgradeLevel();

  74. }

  75.  
  76. void GameAccount::win(){

  77. if (this->getScore() < 200){

  78. setScore(getScore() + 50);

  79. }

  80. else{

  81. setScore(getScore() + 100);

  82. }

  83. printf("\n\t胜利,最新积分为 %d\n", score);

  84. }

  85.  
  86. void GameAccount::lose(){

  87. setScore(getScore() + 30);

  88. printf("\n\t输牌,最新积分为 %d\n", score);

  89. }

  90.  
  91. int GameAccount::getScore(){

  92. return this->score;

  93. }

  94.  
  95. void GameAccount::setScore(int iScore){

  96. this->score = iScore;

  97. }

3.2.状态类

3.2.1.抽象状态类:Level

头文件:

 
  1. #include "GameAccount.h"

  2.  
  3. class Level

  4. {

  5. public :

  6. Level();

  7. // 声明方法

  8. void playCard();

  9. void play();

  10. virtual void doubleScore() = 0;

  11. virtual void changeCards() = 0;

  12. virtual void peekCards() = 0;

  13. // 升级

  14. virtual void upgradeLevel() = 0;

  15. GameAccount* getGameAccount();

  16. void setGameAccount(GameAccount* iGameAccount);

  17. private:

  18. GameAccount* gameAccount;

  19. };

源文件:

 
  1. Level::Level(){}

  2.  
  3. void Level::playCard(){

  4. this->play();

  5. this->doubleScore();

  6. this->changeCards();

  7. this->peekCards();

  8. }

  9.  
  10. void Level::play(){

  11. printf("\t使用基本技能,");

  12. }

  13.  
  14. void Level::setGameAccount(GameAccount* iGameAccount){

  15. this->gameAccount = iGameAccount;

  16. }

  17.  
  18. GameAccount* Level::getGameAccount(){

  19. return gameAccount;

  20. }

 3.2.2.具体状态类:Primary

头文件:

 
  1. class Primary :public Level

  2. {

  3. public:

  4. Primary();

  5. Primary(Level* level);

  6. Primary(GameAccount* ga);

  7. void doubleScore();

  8. void changeCards();

  9. void peekCards();

  10. // 升级

  11. void upgradeLevel();

  12. };

源文件:

 
  1. Primary::Primary(){}

  2.  
  3. Primary::Primary(GameAccount* iGameAccount){

  4. this->setGameAccount(iGameAccount);

  5. }

  6.  
  7. Primary::Primary(Level* level){

  8. getGameAccount()->setLevel(level);

  9. }

  10.  
  11. void Primary::doubleScore(){

  12. return;

  13. }

  14.  
  15. void Primary::changeCards(){

  16. return;

  17. }

  18.  
  19. void Primary::peekCards(){

  20. return;

  21. }

  22.  
  23. void Primary::upgradeLevel(){

  24. if (this->getGameAccount()->getScore() > 150){

  25. this->getGameAccount()->setLevel(new Secondary(this));

  26. printf("\t升级! 级别:SECONDARY\n\n");

  27. }

  28. else{

  29. printf("\n");

  30. }

  31. }

3.2.3.具体状态类:Secondary

头文件:

 
  1. class Secondary :public Level

  2. {

  3. public:

  4. Secondary();

  5. Secondary(Level* level);

  6. void doubleScore();

  7. void changeCards();

  8. void peekCards();

  9. // 升级

  10. void upgradeLevel();

  11. };

源文件:

 
  1. Secondary::Secondary(){

  2.  
  3. }

  4.  
  5. Secondary::Secondary(Level* level){

  6. this->setGameAccount(level->getGameAccount());

  7. getGameAccount()->setLevel(level);

  8. }

  9.  
  10. void Secondary::doubleScore(){

  11. printf("使用胜利双倍积分技能");

  12. }

  13.  
  14. void Secondary::changeCards(){

  15. return;

  16. }

  17.  
  18. void Secondary::peekCards(){

  19. return;

  20. }

  21.  
  22. void Secondary::upgradeLevel(){

  23. if (this->getGameAccount()->getScore() < 150){

  24. this->getGameAccount()->setLevel(new Primary(this));

  25. printf("\t降级! 级别:PRIMARY\n\n");

  26. }

  27. else if (this->getGameAccount()->getScore() > 200){

  28. this->getGameAccount()->setLevel(new Professional(this));

  29. printf("\t升级! 级别:PROFESSIONAL\n\n");

  30. }

  31. }

3.2.4.具体状态类:Professional

头文件:

 
  1. class Professional :public Level

  2. {

  3. public:

  4. Professional();

  5. Professional(Level* level);

  6. void doubleScore();

  7. void changeCards();

  8. void peekCards();

  9. // 升级

  10. void upgradeLevel();

  11. };

源文件:

 
  1. Professional::Professional(){

  2.  
  3. }

  4.  
  5. Professional::Professional(Level* level){

  6. this->setGameAccount(level->getGameAccount());

  7. getGameAccount()->setLevel(level);

  8. }

  9.  
  10. void Professional::doubleScore(){

  11. printf("使用胜利双倍积分技能,");

  12. }

  13.  
  14. void Professional::changeCards(){

  15. printf("使用换牌技能");

  16. }

  17.  
  18. void Professional::peekCards(){

  19. return;

  20. }

  21.  
  22. void Professional::upgradeLevel(){

  23. if (this->getGameAccount()->getScore() < 200){

  24. this->getGameAccount()->setLevel(new Secondary(this));

  25. printf("\t降级! 级别:SECONDARY\n\n");

  26. }

  27. else if (this->getGameAccount()->getScore() > 250){

  28. this->getGameAccount()->setLevel(new Final(this));

  29. printf("\t升级! 级别:FINAL\n\n");

  30. }

  31. }

3.2.5.具体状态类:Final

头文件:

 
  1. class Final :public Level

  2. {

  3. public:

  4. Final();

  5. Final(Level* level);

  6. void doubleScore();

  7. void changeCards();

  8. void peekCards();

  9. // 升级

  10. void upgradeLevel();

  11. };

源文件:

 
  1. Final::Final(){

  2.  
  3. }

  4.  
  5. Final::Final(Level* level){

  6. this->setGameAccount(level->getGameAccount());

  7. getGameAccount()->setLevel(level);

  8. }

  9.  
  10. void Final::doubleScore(){

  11. printf("使用胜利双倍积分技能,");

  12. }

  13.  
  14. void Final::changeCards(){

  15. printf("使用换牌技能,");

  16. }

  17.  
  18. void Final::peekCards(){

  19. printf("使用偷看卡牌技能");

  20. }

  21.  
  22. void Final::upgradeLevel(){

  23. if (this->getGameAccount()->getScore() < 250){

  24. this->getGameAccount()->setLevel(new Professional(this));

  25. printf("\t降级! 级别:PROFESSIONAL\n\n");

  26. }

  27. else{

  28. printf("\t%s 已经是最高级\n\n", this->getGameAccount()->getName().c_str());

  29. }

  30. }

3.3.客户端代码示例及结果

客户端代码创建了一个游戏账户Jungle,初始积分为100分,级别为Primary,即入门级,Jungle一共玩了5局牌。

 
  1. #include "GameAccount.h"

  2. #include "Level.h"

  3.  
  4. int main()

  5. {

  6. GameAccount *jungle = new GameAccount("Jungle");

  7.  
  8. for (int i = 0; i < 5; i++){

  9. printf("第%d局:\n", i + 1);

  10. jungle->playCard();

  11. }

  12.  
  13. printf("\n\n");

  14. system("pause");

  15. return 0;

  16. }

结果如下:

 上面的代码不管Jungle当前是什么级别,都统一地调用了上下文类封装好的方法playcard(),即外界并不知道不同级别内部的具体实现细节。运行结果显示,Jungle的在不同的状态(级别)下能够表现不同的行为(不同的技能),并且能够不断改变自身的状态(升级或降级)

上述代码源码请访问:https://github.com/FengJungle/DesignPattern

4.总结

优点:

  • 状态模式封装了状态转换的规则,只给外界暴露了统一的接口,客户端可以无差别地调用该接口(如上述实例的客户端代码)
  • 状态模式将所有与具体状态有关的行为放到一个类(具体状态类)中,只需要注入(依赖)不同的状态类对象到上下文类中,即可使上下文中拥有不同的行为

缺点:

  • 状态模式增加了系统中类的个数(不同的具体状态类)
  • 结构相对复杂(如前述实例的UML图),代码逻辑也较复杂
  • 如果要增加新的状态,需要修改负责状态转换的代码,不符合开闭原则(如上述实例,如果增加了一个中间级别,是不是得修改很多状态转换的逻辑?

适用环境:

  • 对象的行为根据它的状态的改变而不同
  • 代码中含有大量与对象状态有关的判断逻辑(if……else……或switch……case……)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值