【C#设计模式(21)——状态模式(State Pattern)】
前言
状态模式:在对象内部发生改变时改变其行为,使得对象在不同的状态下具有不同的行为表现。
代码
#region 状态模式-类
/// 抽象 交通灯状态
public abstract class TrafficLightState
{
public abstract void Display();
}
//红灯
public class RedLight : TrafficLightState
{
public override void Display()
{
Console.WriteLine("红灯停");
}
}
//绿灯
public class GreenLight : TrafficLightState
{
public override void Display()
{
Console.WriteLine("绿灯行");
}
}
//黄灯
public class YellowLight : TrafficLightState
{
public override void Display()
{
Console.WriteLine("黄灯等待");
}
}
//交通灯上下文
public class TrafficLightContext
{
private TrafficLightState trafficLight;
public TrafficLightContext()
{
trafficLight = new RedLight();
}
public void SetTrafficLightState(TrafficLightState trafficLight)
{
this.trafficLight = trafficLight;
}
public void Display()
{
trafficLight.Display();
}
}
#endregion
#region 状态模式-枚举
//交通灯状态枚举
public enum TrafficLightEnum
{
Red,
Green,
Yellow
}
//交通灯枚举状态显示设置类
public class TrafficLightEnumState
{
private TrafficLightEnum state;
public void SetState(TrafficLightEnum state)
{
this.state = state;
}
public void Display()
{
switch (state)
{
case TrafficLightEnum.Red:
Console.WriteLine("红灯停");
break;
case TrafficLightEnum.Green:
Console.WriteLine("绿灯行");
break;
case TrafficLightEnum.Yellow:
Console.WriteLine("黄灯等待");
break;
}
}
}
//交通灯上下文(枚举设置)
public class TrafficLightEnumContext
{
private TrafficLightEnumState trafficLight;
public TrafficLightEnumContext()
{
trafficLight = new TrafficLightEnumState();
trafficLight.SetState(TrafficLightEnum.Red);
}
public void SetTrafficLightState(TrafficLightEnum state)
{
trafficLight.SetState(state);
}
public void Display()
{
trafficLight.Display();
}
}
#endregion
/*
* 行为型模式:Behavioral Pattern
* 状态模式:State Pattern
*/
internal class Program
{
/*
* 行为型模式:Behavioral Pattern
* 状态模式:State Pattern
*/
static void Main(string[] args)
{
//类模式
Console.WriteLine("类模式......");
TrafficLightContext trafficLight = new TrafficLightContext();
trafficLight.Display();
trafficLight.SetTrafficLightState(new GreenLight());
trafficLight.Display();
trafficLight.SetTrafficLightState(new YellowLight());
trafficLight.Display();
//枚举模式
Console.WriteLine("枚举模式......");
TrafficLightEnumContext trafficLightEnumContext = new TrafficLightEnumContext();
trafficLightEnumContext.Display();
trafficLightEnumContext.SetTrafficLightState(TrafficLightEnum.Green);
trafficLightEnumContext.Display();
trafficLightEnumContext.SetTrafficLightState(TrafficLightEnum.Yellow);
trafficLightEnumContext.Display();
Console.ReadLine();
}
}