命令模式
这个模式主要用到类的封装调用,示例:
public interface ICommand { void Execute(); } public class Light { private bool _ison; public Light() { _ison = false; Off(); } public bool On() { _ison =true; Console.WriteLine("Light is on,see it"); return true; } public bool Off() { if (!_ison) { Console.WriteLine("At frist.The light is off"); } else { Console.WriteLine("At Last.The light is off"); } return false; } } public class LightOnCommand : ICommand { public Light Light { get; set; } public LightOnCommand(Light light) { Light = light; } public void Execute() { Light.On(); } } public class GarageDoorOpen:ICommand { public Light Light { get; set; } public GarageDoorOpen(Light light) { Light = light; } public void Execute() { Light.Off(); } public void Up() { Light.Off(); } public void Down() { Light.On(); } public void Stop() { Light.Off(); } } public class SimpleRemoteControl { public ICommand Slot; //public SimpleRemoteControl() { } public void SetCommand(ICommand command) { Slot = command; } public void ButtonWasPressed() { Slot.Execute(); } } class Program { static void Main(string[] args) { var simpleRemoteControl=new SimpleRemoteControl(); var light=new Light(); var lightOn=new LightOnCommand(light); simpleRemoteControl.SetCommand(lightOn); simpleRemoteControl.ButtonWasPressed(); light.Off(); var garageDoorOpen = new GarageDoorOpen(light); simpleRemoteControl.SetCommand(garageDoorOpen); garageDoorOpen.Down(); simpleRemoteControl.ButtonWasPressed(); Console.ReadLine();
结果:At frist.The light is off
Light is on,see it
At Last.The light is off
Light is on,see it
At Last.The light is off