命令模式: 允许把动作请求者和动作执行者解耦
1、这里拿遥控器和家用电器的例子来说,遥控器就是动作请求者,动作执行者就是家用电器
2、以下只是一个简答的实现可扩展性设计思路,仅供参考
1、家用电器(灯泡)
Light类对象
using System;
using System.Collections.Generic;
using System.Text;
namespace DesignModel
{
public class Light
{
public void On()
{
Console.WriteLine("开灯");
}
public void Off()
{
Console.WriteLine("关灯");
}
}
}
2、遥控器
RemoteControl类对象
using System;
using System.Collections.Generic;
using System.Text;
namespace DesignModel
{
class RemoteControl
{
public ICommond Slot { get; set; }
/// <summary>
/// 按钮执行
/// </summary>
public void ButtonWasPressed() {
Slot.Execute();
}
}
}
3、开灯命令
LighOnCommond 类对象
using System;
using System.Collections.Generic;
using System.Text;
namespace DesignModel
{
public class LighOnCommond : ICommond
{
private readonly Light light;
public LighOnCommond(Light _light) {
this.light = _light;
}
public void Execute() {
this.light.On();
}
}
}
4、关灯命令
LightOffCommond 类对象
using System;
using System.Collections.Generic;
using System.Text;
namespace DesignModel
{
public class LightOffCommond:ICommond
{
private readonly Light light;
public LightOffCommond(Light _light)
{
this.light = _light;
}
public void Execute()
{
this.light.Off();
}
}
}
5、执行命令
using System;
namespace DesignModel
{
class Program
{
static void Main(string[] args)
{
RemoteControl rc = new RemoteControl();
Light light = new Light();
LighOnCommond lightOn = new LighOnCommond(light);
//1、开灯
rc.Slot = lightOn;
rc.ButtonWasPressed();
//2、关灯
LightOffCommond lightOff = new LightOffCommond(light);
rc.Slot = lightOff;
rc.ButtonWasPressed();
}
}
}
6、效果如下所示