一、概述
在面向对象软件设计时,常常碰到某一个对象由于状态的不同而有不同的行为。如果用if else或是switch case等方法处理,对象操作及对象的状态就耦合在一起,碰到复杂的情况就会造成代码结构的混乱。在这种情况下,就可以使用状态模式来解决问题。
二、状态模式
状态模式允许一个对象在其内部状态改变时改变它的行为,使对象看起来似乎修改了它的类。
状态模式的结构图如下
Context代表需要改变状态的那个对象,它维护了一个State实例,该实例定义了对象的当前状态。
State定义了一个抽象类或是接口,用以封装与特定状态相关的行为。
ConcreteState实现了State定义的行为。
三、示例
本文实现一个电灯开关状态,以此为例介绍状态模式的应用。
首先定义状态接口
1 public interface LightState
2 {
3 void PressSwitch(Light light);
4 }
接着实现具体的状态
1 public class LightOn : LightState
2 {
3 public void PressSwitch(Light light)
4 {
5 Console.WriteLine("Light Off");
6 light.State = new LightOff();
7 }
8 }
9
10 public class LightOff : LightState
11 {
12 public void PressSwitch(Light light)
13 {
14 Console.WriteLine("Light On");
15 light.State = new LightOn();
16 }
17 }
然后定义拥有该状态的对象即电灯
1 public class Light
2 {
3 public LightState State;
4
5 public Light()
6 {
7 State = new LightOff();
8 }
9
10 public void PressSwtich()
11 {
12 State.PressSwitch(this);
13 }
14 }
最后看一下如何调用
1 static void Main(string[] args)
2 {
3 Light light = new Light();
4 light.PressSwtich();
5 light.PressSwtich();
6 light.PressSwtich();
7
8 Console.ReadLine();
9 }
输出结果如下
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAARIAAACHCAIAAABViUEwAAAal0lEQVR4nO2da3Mb13mA33N2QUpO0ulP6KRxnInl2GO7Sf5LHetmSRYpW7JkyZET26ISKWl/QGcai5K/dqbTi0XqBuwdkOumiSyRWAAkdScB7OJG3IHF5fTDARZLAKRISZZk8X3mnZ3FwWKxIM+Dc8fC9NSXk5OTJyZOvbTt9UKTLVj1SNKJ2u25LLuRaEYsNpdqxazarXT1ZiK/YBXmE+UFq75g1eeTtQWrHotX7mRasXhlPlm7aTt8Zy5R5TvzyVo04cxZzZl75WjC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