状态模式:
状态模式(State),当一个对象的内在状态改变时允许改变其行为,这个对象看起来像是改变了其类。
结构图
代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 状态模式
{
public abstract class State
{
public abstract void WriteProgram(Work w);
}
public class ForenoonState : State
{
public override void WriteProgram(Work w)
{
if (w.Hour < 12)
{
Console.WriteLine("当前时间:{0} 点, 精神百倍",w.Hour);
}
else
{
w.SetState(new NoonState());w.WriteProgram();
}
}
}
public class NoonState : State
{
public override void WriteProgram(Work w)
{
if (w.Hour < 13)
{
Console.WriteLine("当前时间:{0} 点, 饿了,困了,累了", w.Hour);
}
}
}
public class Work
{
private State current;
public Work()
{
current = new ForenoonState();
}
private double hour;
public double Hour
{
get { return hour; }
set { hour = value; }
}
private bool finish = false;
public bool TaskFinished
{
get { return finish; }
set { finish = value; }
}
public void SetState(State s)
{
current = s;
}
public void WriteProgram()
{
current.WriteProgram(this); //此处的this指的是 实例化的对象
}
}
class Program
{
static void Main(string[] args)
{
Work eme = new Work();
eme.Hour = 9;
eme.TaskFinished = false;
eme.WriteProgram();
Console.ReadKey();
}
}
}
从上边代码我们可以看出我们将判断都写到了相应的类里边,简化了判断的难度,并且各个子类相互之间的依赖都减少了,使得编程变得更加方便。
特点:
1. 将特定的状态相关的行为局部化,并将不同状态的行为分隔开。
2. 子类之间依赖减少