在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
理解:当对象有多个状态时,把每个状态的行为写到各自的状态类里面去,当切换状态时,调用的行为也就自动切换了。 和策略模式很像,不过策略是针对外部的,而状态是针对内部的 代码: using System.Windows.Forms;
namespace DesignMode.State { //对象类 public class Computer { //系统要求 private string _request; public string Request { get { return _request; } set { _request = value; } } private OperatingSystem _os; public OperatingSystem OS { get { return _os; } set { _os = value; } } public Computer(OperatingSystem os) { this._os = os; } public void Run() { //先改状态,再执行状态对应的行为 _os.ChangeOS(this); _os.Run(); } } //抽象的对象状态类 public abstract class OperatingSystem { public abstract void ChangeOS(Computer computer); public abstract void Run(); } public class Vista : OperatingSystem { //子状态根据对象的系统要求属性来更改对应的状态 public override void ChangeOS(Computer computer) { if (computer.Request.Equals("W")) { computer.OS = new Windows(); } else if (computer.Request.Equals("L")) { computer.OS = new Linux(); } } public override void Run() { MessageBox.Show("运行Vista系统"); } } public class Windows : OperatingSystem { public override void ChangeOS(Computer computer) { if (computer.Request.Equals("V")) { computer.OS = new Vista(); } else if (computer.Request.Equals("L")) { computer.OS = new Linux(); } } public override void Run() { MessageBox.Show("运行Windows系统"); } } public class Linux : OperatingSystem { public override void ChangeOS(Computer computer) { if (computer.Request.Equals("W")) { computer.OS = new Windows(); } else if (computer.Request.Equals("V")) { computer.OS = new Vista(); } } public override void Run() { MessageBox.Show("运行Linux系统"); } } } 客户端代码:
private void btn_State_Click(object sender, EventArgs e)
{
|
请发表评论