| 名称 | State |
| 结构 | ![]() |
| 意图 | 允许一个对象在其内部状态改变时改变它的行为。对象看起来似乎修改了它的类。 |
| 适用性 |
|
| Code Example |
1 // State2 ![]() 3 // Intent: "Allow an object to alter its behavior when its internal state 4 // changes. The object will appear to change its class". 5 ![]() 6 // For further information, read "Design Patterns", p305, Gamma et al.,7 // Addison-Wesley, ISBN:0-201-63361-28 ![]() 9 /* Notes:10 * 11 * A finite state machine is an appropriate construct to use for a class whose12 * reaction to stimuli depends on previous behavior. In the past, each 13 * method in the class was coded as a switch statement, switching on the state. 14 * If a new state was added, then each method had to be edited. 15 * 16 * With the state design pattern, functionality specific to a state is placed 17 * in a helper class, and the main class delegates those methods that are 18 * state-specific to such helper classes. 19 * 20 */21 22 namespace State_DesignPattern23 {24 using System;25 ![]() 26 abstract class State 27 {28 protected string strStatename; 29 ![]() 30 abstract public void Pour();31 // do something state-specific here32 }33 ![]() 34 class OpenedState : State 35 { 36 public OpenedState ()37 {38 strStatename = "Opened";39 }40 override public void Pour()41 {42 Console.WriteLine(" pouring ");43 Console.WriteLine(" pouring ");44 Console.WriteLine(" pouring ");45 }46 }47 48 class ClosedState : State 49 { 50 public ClosedState()51 {52 strStatename = "Closed";53 }54 override public void Pour()55 {56 Console.WriteLine("ERROR - bottle is closed - cannot pour");57 }58 }59 ![]() 60 class ContextColaBottle 61 {62 public enum BottleStateSetting {63 Closed,64 Opened65 };66 ![]() 67 // If teh state classes had large amounts of instance data,68 // we could dynamically create them as needed - if this demo69 // they are tiny, so we just create them as data members70 OpenedState openedState = new OpenedState();71 ClosedState closedState = new ClosedState();72 ![]() 73 public ContextColaBottle ()74 {75 // Initialize to closed76 CurrentState = closedState;77 }78 ![]() 79 private State CurrentState;80 81 public void SetState(BottleStateSetting newState)82 {83 if (newState == BottleStateSetting.Closed)84 {85 CurrentState = closedState;86 }87 else 88 {89 CurrentState = openedState;90 }91 }92 ![]() 93 public void Pour()94 {95 CurrentState.Pour();96 } 97 }98 ![]() 99 /// <summary>100 /// Summary description for Client.101 /// </summary>102 public class Client103 {104 public static int Main(string[] args)105 {106 ContextColaBottle contextColaBottle = new ContextColaBottle();107 ![]() 108 Console.WriteLine("initial state is closed");109 ![]() 110 Console.WriteLine("Now trying to pour");111 contextColaBottle.Pour();112 ![]() 113 Console.WriteLine("Open bottle");114 contextColaBottle.SetState(ContextColaBottle.BottleStateSetting.Opened);115 ![]() 116 Console.WriteLine("Try to pour again");117 contextColaBottle.Pour();118 ![]() 119 return 0;120 }121 }122 }123 ![]() 124 ![]() |




*


