4.8 State(状态)
【返回目录】
现在,拥有私家车的朋友越来越多,就算你还没有属于自己的座驾,但至少你也一定见过不少汽车了。
所谓没有规矩不成方圆,开车也有开车的规矩,比如开车前要注意检查车门是否都已经关好,如果没关好,交警叔叔见到了可不答应,就算没有被交警看到,为了你和你的亲友的安全,也不应该大而化之嘛。
我们就用计算机程序设计的思想来描述一下这种场景,假设我们有Car这个类,并且我们还创建了AbstractState这样一个抽象类,继承自它的有OpenState和CloseState(而不是仅仅在Car中设置一个bool属性值),这样做的好处就是为了易于维护和扩展。AbstractState具有Drive的方法,而Drive在不同的状态下有不同的反映,Car则通过它当前状态的Drive方法来驾驶车辆,而不是把Drive的各种逻辑也封装在Car中。
1: using System;
2:
3: namespace Autumoon.DesignPatterns.State
4: {
5: public enum DoorStateSetting
6: {
7: Closed = 0,
8: Opened
9: };
10:
11: public abstract class AbstractState
12: {
13: public string StateName { get; set; }
14:
15: abstract public void Drive();
16: }
17:
18: public class OpenedState : AbstractState
19: {
20: public OpenedState()
21: {
22: this.StateName = "Opened";
23: }
24:
25: override public void Drive()
26: {
27: Console.WriteLine("Error: The car cannot be drived as its door(s) is open.");
28: }
29: }
30:
31: public class ClosedState : AbstractState
32: {
33: public ClosedState()
34: {
35: this.StateName = "Closed";
36: }
37:
38: override public void Drive()
39: {
40: Console.WriteLine("The car is running.");
41: }
42: }
43:
44: public class Car
45: {
46: public AbstractState CurrentState { get; set; }
47:
48: public Car()
49: {
50: this.CurrentState = new ClosedState();
51: }
52:
53: public void SetState(DoorStateSetting newState)
54: {
55: this.CurrentState = ((newState == DoorStateSetting.Closed)
56: ? new ClosedState() as AbstractState
57: : new OpenedState() as AbstractState);
58: }
59:
60: public void Drive()
61: {
62: this.CurrentState.Drive();
63: }
64: }
65: }
那么我们就来体验一下驾驶的乐趣吧,注意安全哦!
1: static void Main(string[] args)
2: {
3: #region State
4: Car contextColaBottle = new Car();
5: Console.WriteLine("Doors' initial state is closed.");
6:
7: Console.WriteLine("Now drive.");
8: contextColaBottle.Drive();
9:
10: Console.WriteLine("Open the door.");
11: contextColaBottle.SetState(DoorStateSetting.Opened);
12:
13: Console.WriteLine("Now Drive.");
14: contextColaBottle.Drive();
15: #endregion
16:
17: Console.ReadLine();
18: }
转载请注明出处。版权所有©2022 麦机长,保留所有权利。