using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _020状态模式
{
public interface LightState
{
void Press(Light light);
}
public class TurnOff : LightState
{
public void Press(Light light)
{
light.State = new TurnOn();
Console.WriteLine("turn on the light");
}
}
public class TurnOn : LightState
{
public void Press(Light light)
{
light.State = new TurnOff();
Console.WriteLine("turn off the light");
}
}
public class Light
{
public LightState State;
public Light()
{
this.State = new TurnOff();
}
public void Press()
{
State.Press(this);
}
}
internal class Program
{
private static void Main(string[] args)
{
Light light = new Light();
light.Press();
light.Press();
light.Press();
/*
* 状态模式
*
* 利用接口实现不同的逻辑,根据逻辑实现需求
*
* 与策略模式相似
*
* 但策略模式偏向外部实现逻辑,状态模式比较偏向内部实现逻辑,
*
* 外部只需要调用接口则可以改变对象内部的状态,实现不同的逻辑
*
*/
Console.ReadKey();
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _020状态模式
{
public interface LightState
{
void Press(Light light);
}
public class TurnOff : LightState
{
public void Press(Light light)
{
light.State = new TurnOn();
Console.WriteLine("turn on the light");
}
}
public class TurnOn : LightState
{
public void Press(Light light)
{
light.State = new TurnOff();
Console.WriteLine("turn off the light");
}
}
public class Light
{
public LightState State;
public Light()
{
this.State = new TurnOff();
}
public void Press()
{
State.Press(this);
}
}
internal class Program
{
private static void Main(string[] args)
{
Light light = new Light();
light.Press();
light.Press();
light.Press();
/*
* 状态模式
*
* 利用接口实现不同的逻辑,根据逻辑实现需求
*
* 与策略模式相似
*
* 但策略模式偏向外部实现逻辑,状态模式比较偏向内部实现逻辑,
*
* 外部只需要调用接口则可以改变对象内部的状态,实现不同的逻辑
*
*/
Console.ReadKey();
}
}
}