命令模式

时间:2022-11-02 13:59:57


命令模式

using System;
using System.Collections.Generic;

namespace 命令模式
{
class Program
{
static void Main(string[] args)
{

//把电视机、电灯准备好,把各种指令准备好,拿出遥控器把各种指令收纳其中
//最后调用遥控器的方法执行各种指令
//命令的接收方
Tv tv=new Tv();
Light light=new Light();
//命令
LighOn lighOn=new LighOn(light);
LighOff lighOff=new LighOff(light);
TvOn tvOn=new TvOn(tv);
TvOff tvOff=new TvOff(tv);
TvSwitch tvSwitch=new TvSwitch(tv);
//添加到RemoteControl中不同命令的集合中
RemoteControl remoteControl=new RemoteControl();
remoteControl.AddOnCommand(tvOn);
remoteControl.AddOnCommand(lighOn);
remoteControl.AddOffCommand(tvOff);
remoteControl.AddOffCommand(lighOff);
remoteControl.AddSwitchCommand(tvSwitch);
//执行命令
remoteControl.PressOnButton(0);
remoteControl.PressOffButton(0);
remoteControl.PressOnButton(1);
remoteControl.PressOffButton(1);
Console.ReadKey();
}
}


/// <summary>
/// 指令的执行
/// </summary>
public interface IControl
{
void Execute();
}

/// <summary>
/// 把电灯、电视机抽象成类。
/// </summary>
public class Tv
{
public void TurnOn()
{
Console.WriteLine("电视机打开了");
}

public void TurnOff()
{
Console.WriteLine("电视机关闭了");
}

public void SwitchChannel()
{
Console.WriteLine("电视机切换频道");
}

}

public class Light
{
public void TurnOn()
{
Console.WriteLine("电灯打开了");
}

public void TurnOff()
{
Console.WriteLine("电灯关闭了");
}
}

//Tv类的TurnOn(),TurnOff(),SwitchChannel(),Light类的TurnOn(),TurnOff()
//这些方法都会通过执行IController的Execute方法被触发。把每一种动作抽象成类,并实现IControl接口
#region
public class LighOn:IControl
{
private Light light;
public LighOn(Light light)
{
this.light = light;
}
public void Execute()
{
light.TurnOn();
}
}


public class LighOff:IControl
{

private Light light;
public LighOff(Light light)
{
this.light = light;
}
public void Execute()
{
light.TurnOff();
}
}

public class TvOn : IControl
{

private Tv tv;
public TvOn(Tv tv)
{
this.tv = tv;
}
public void Execute()
{
tv.TurnOn();
}
}

public class TvOff : IControl
{

private Tv tv;
public TvOff(Tv tv)
{
this.tv = tv;
}
public void Execute()
{
tv.TurnOff();
}
}

public class TvSwitch:IControl
{
private Tv tv;
public TvSwitch(Tv tv)
{
this.tv = tv;
}
public void Execute()
{
tv.SwitchChannel();
}
}

#endregion


//电视机和电灯有了,触发各种动作的类有了,遥控器该装下这些指令(提供装下指令的方法)并提供方法供客户端调用
public class RemoteControl
{
private IList<IControl> onCommands=new List<IControl>();
private IList<IControl> offCommands=new List<IControl>();
private IList<IControl> switchCommands=new List<IControl>();

//添加命令
public void AddOnCommand(IControl iControl)
{
onCommands.Add(iControl);
}

public void AddOffCommand(IControl iControl)
{
offCommands.Add(iControl);
}
public void AddSwitchCommand(IControl iControl)
{
switchCommands.Add(iControl);
}

//执行命令
public void PressOnButton(int number)
{
onCommands[number].Execute();
}

public void PressOffButton(int number)
{
offCommands[number].Execute();
}

public void PressSwitchButton(int number)
{
switchCommands[number].Execute();
}
}
}