命令模式是对命令的封装.命令模式把发出命令的责任和执行命令的责任分割开,委派给不同的对象.该模式的示意类图如下:
下面是一个Command模式的例子(模仿<Java与模式>中的例子).
现有一个录音机(AudioPlayer),他有播放(Play),到带(Rewind)和停止(Stop)三个功能,利用Command模式实现中,录音机(AudioPlayer)则为Receiver对象,将录音机的键盘作为Invoker对象,因为客户是通过他去执行播放,倒带,停止的功能(命令).
首先:定义录音机对象
/**//// <summary>
/// 录音机对象,该对象充当Receiver角色
/// </summary> public class AudioPlayer
{
public AudioPlayer()
{
}
/**//// <summary>
/// 播放
/// </summary>
public void Play()
{
Console.WriteLine("Playing");
}
/**//// <summary>
/// 停止
/// </summary>
public void Stop()
{
Console.WriteLine("Stoping");
}
/**//// <summary>
/// 倒带
/// </summary>
public void Rewind()
{
Console.WriteLine("Rewinding");
}
} 接下来定义命令对象,在这里,我采用一个抽象类AbstractCommand(ICommand角色)做为所有具体命令类的父类,所有具体命令类都要继承自该抽象类:
public abstract class AbstractCommand
{
protected AudioPlayer _player;
public AbstractCommand(AudioPlayer player)
{
this._player = player;
}
public abstract void Execute();
} 具体命令对象如下:
/**//// <summary>
/// 播放命令
/// </summary> public class PlayCommand : AbstractCommand
{
public PlayCommand(AudioPlayer player) : base(player)
{
}
ICommand 成员#region ICommand 成员
public override void Execute()
{
_player.Play();
}
#endregion
}
/**//// <summary>
/// 停止命令
/// </summary> public class StopCommand : AbstractCommand
{
public StopCommand(AudioPlayer player) : base(player)
{
}
ICommand 成员#region ICommand 成员
public override void Execute()
{
_player.Stop();
}
#endregion
}
/**//// <summary>
/// 倒带命令
/// </summary> public class RewindCommand : AbstractCommand
{
public RewindCommand(AudioPlayer player) : base(player)
{
}
ICommand 成员#region ICommand 成员
public override void Execute()
{
_player.Rewind();
}
#endregion
} 接下来定义键盘对象KeyPad(Invoker角色):
/**//// <summary>
/// 录音机键盘对象,该对象充当Invoker角色
/// </summary> public class KeyPad
{
private AbstractCommand _playCmd;
private AbstractCommand _stopCmd;
private AbstractCommand _rewindCmd;
public KeyPad(AbstractCommand playCmd,AbstractCommand stopCmd,AbstractCommand rewindCmd)
{
this._playCmd = playCmd;
this._stopCmd = stopCmd;
this._rewindCmd = rewindCmd;
}
public void Play()
{
_playCmd.Execute();
}
public void Stop()
{
_stopCmd.Execute();
}
public void Rewind()
{
_rewindCmd.Execute();
}
} 现在,客户端就可以这样控制录音机了:
AudioPlayer player = new AudioPlayer(); //定义receiver对象
/**//*各个具体命令对象*/
AbstractCommand playCmd = new PlayCommand(player);
AbstractCommand stopCmd = new StopCommand(player);
AbstractCommand rewindCmd = new RewindCommand(player);
KeyPad pad = new KeyPad(playCmd,stopCmd,rewindCmd); //定义invoker对象
/**//*通过invoker进行命令的执行*/
pad.Play();
pad.Rewind();
pad.Stop();
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请
点击举报。