State模式允许对象在内部状态变化时,变更其行为,并修改其类;
优点:
定位指定状态的行为,并且针对不同状态来划分行为,使状态转换显式进行;
适用:
对象的行为依赖于其状态,并且该对象必须在运行时根据其状态修改其行为;
操作具有大量的以及多部分组成的取决于对象状态的条件语句;
public class Bank
{
private int hour;
private Person person;
public void SetClock(int hour)
{
this.hour = hour;
Console.WriteLine($"现在时间是{hour}点");
if (hour > 8 && hour < 18)
ChangeState(Customer.GetInstance());
else ChangeState(Thief.GetInstance());
}
public void ChangeState(Person person)
{
this.person = person;
person.SayHi();
}
}
public interface Person
{
void SayHi();
}
public class Customer : Person
{
private static Customer customer = new Customer();
public static Customer GetInstance() => customer;
public void SayHi()
{
Console.WriteLine("我是客户,我来取钱");
}
}
public class Thief : Person
{
private static Thief thief = new Thief();
public static Thief GetInstance() => thief;
public void SayHi()
{
Console.WriteLine("我是窃贼,我来偷钱");
}
}
public static void StatePatternTest()
{
Bank bank = new Bank();
int hour = 0;
while (true)
{
bank.SetClock(hour);
hour++;
hour %= 24;
Thread.Sleep(1000);
}
}
标签:Customer,hour,Person,Pattern,void,person,State,设计模式,public
From: https://www.cnblogs.com/zhangdezhang/p/17749201.html