一,什么是状态设计模式?
1,定义对象间的一种一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新。
2,当一个对象的内部状态改变时允许改变其行为,这个对象看起来像是改变了其类
二,如下代码:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _18.状态者模式 { class Program { static void Main(string[] args) { State s = new State(); s.Say(); s.Say(); s.Say(); } } public interface People { void Say(State s); } public class Chinese : People { public void Say(State s) { Console.WriteLine("说中文"); s.people = new English(); } } public class English : People { public void Say(State s) { Console.WriteLine("说英文"); s.people = new Chinese(); } } public class State { public People people { get; set; } public State() { people = new Chinese(); } public void Say() { people.Say(this); } } }
使用场景: State模式在实际使用中比较多,适合"状态的切换".因为我们经常会使用If elseif else 进行状态切换, 如果针对状态的这样判断切换反复出现,我们就要联想到是否可以采取State模式了.