标签:
结构 | |
意图 | 允许一个对象在其内部状态改变时改变它的行为。对象看起来似乎修改了它的类。 |
适用性 |
|
1 using System; 2 3 abstract class State 4 { 5 protected string strStatename; 6 7 abstract public void Pour(); 8 // do something state-specific here 9 } 10 11 class OpenedState : State 12 { 13 public OpenedState () 14 { 15 strStatename = "Opened"; 16 } 17 override public void Pour() 18 { 19 Console.WriteLine("...pouring..."); 20 Console.WriteLine("...pouring..."); 21 Console.WriteLine("...pouring..."); 22 } 23 } 24 25 class ClosedState : State 26 { 27 public ClosedState() 28 { 29 strStatename = "Closed"; 30 } 31 override public void Pour() 32 { 33 Console.WriteLine("ERROR - bottle is closed - cannot pour"); 34 } 35 } 36 37 class ContextColaBottle 38 { 39 public enum BottleStateSetting { 40 Closed, 41 Opened 42 }; 43 44 // If teh state classes had large amounts of instance data, 45 // we could dynamically create them as needed - if this demo 46 // they are tiny, so we just create them as data members 47 OpenedState openedState = new OpenedState(); 48 ClosedState closedState = new ClosedState(); 49 50 public ContextColaBottle () 51 { 52 // Initialize to closed 53 CurrentState = closedState; 54 } 55 56 private State CurrentState; 57 58 public void SetState(BottleStateSetting newState) 59 { 60 if (newState == BottleStateSetting.Closed) 61 { 62 CurrentState = closedState; 63 } 64 else 65 { 66 CurrentState = openedState; 67 } 68 } 69 70 public void Pour() 71 { 72 CurrentState.Pour(); 73 } 74 } 75 76 /// <summary> 77 /// Summary description for Client. 78 /// </summary> 79 public class Client 80 { 81 public static int Main(string[] args) 82 { 83 ContextColaBottle contextColaBottle = new ContextColaBottle(); 84 85 Console.WriteLine("initial state is closed"); 86 87 Console.WriteLine("Now trying to pour"); 88 contextColaBottle.Pour(); 89 90 Console.WriteLine("Open bottle"); 91 contextColaBottle.SetState(ContextColaBottle.BottleStateSetting.Opened); 92 93 Console.WriteLine("Try to pour again"); 94 contextColaBottle.Pour(); 95 96 return 0; 97 } 98 }
标签:
原文地址:http://www.cnblogs.com/ziranquliu/p/4669318.html