public class LightOnCommand:ICommand
{
Light light;
public LightOnCommand(Light light)
{
this.light = light;
}
public void Execute()
{
light.On();
}
}
public class LightOffCommand : ICommand
{
Light light;
public LightOffCommand(Light light)
{
this.light = light;
}
public void Execute()
{
light.Off();
}
}
public class Light
{
public void On()
{
Console.WriteLine("打开电灯");
}
public void Off()
{
Console.WriteLine("关闭电灯");
}
}
public class NoCommand:ICommand
{
public void Execute()
{
}
}
public class RemoteControl
{
ICommand[] onCommands;
ICommand[] offCommands;
public RemoteControl()
{
onCommands = new ICommand[7];
offCommands = new ICommand[7];
}
public void SetCommand(int slot, ICommand oncommand, ICommand offCommand)
{
onCommands[slot] = oncommand;
offCommands[slot] = offCommand;
}
public void Button1Click(int slot)
{
onCommands[slot].Execute();
}
public void Button2Click(int slot)
{
offCommands[slot].Execute();
}
}
class Program
{
static void Main(string[] args)
{
RemoteControl rc = new RemoteControl();
Light light = new Light();
ICommand loc = new LightOnCommand(light);
ICommand lfc = new LightOffCommand(light);
ICommand nc = new NoCommand();
for (int i = 0; i < 7; i++)
{
rc.SetCommand(i, nc, nc);
}
rc.SetCommand(0, loc, lfc);
rc.Button1Click(0);
rc.Button2Click(0);
Console.Read();
}
}