状态模式

作者:追风剑情 发布于:2016-6-5 15:31 分类:设计模式

应用场景:当有多个状态时,不同的状态对应不同的行为

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. namespace StateTest
  7. {
  8. class Program
  9. {
  10. static void Main(string[] args)
  11. {
  12. Context context = new Context();
  13. context.SetState(new StateA());//设置初始状态
  14. Console.WriteLine(context.GetState().ToString());
  15.  
  16. context.Next();
  17. Console.WriteLine(context.GetState().ToString());
  18.  
  19. context.Next();
  20. Console.WriteLine(context.GetState().ToString());
  21.  
  22. Console.Read();
  23. }
  24. }
  25.  
  26. interface IState
  27. {
  28. string ToString();
  29. void Next(Context c);
  30. }
  31.  
  32. class StateA : IState
  33. {
  34. public string ToString()
  35. {
  36. return "State A";
  37. }
  38. public void Next(Context c)
  39. {
  40. c.SetState(new StateB());
  41. }
  42. }
  43.  
  44. class StateB : IState
  45. {
  46. public string ToString()
  47. {
  48. return "State B";
  49. }
  50. public void Next(Context c)
  51. {
  52. c.SetState(new StateC());
  53. }
  54. }
  55.  
  56. class StateC : IState
  57. {
  58. public string ToString()
  59. {
  60. return "State C";
  61. }
  62. public void Next(Context c)
  63. {
  64. c.SetState(new StateA());
  65. }
  66. }
  67.  
  68. class Context
  69. {
  70. private IState state;
  71.  
  72. public IState GetState()
  73. {
  74. return state;
  75. }
  76.  
  77. public void SetState(IState state)
  78. {
  79. this.state = state;
  80. }
  81.  
  82. public void Next()
  83. {
  84. state.Next(this);
  85. }
  86. }
  87. }

运行效果

2222.jpg

标签: Algorithms

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号