命令模式是對(duì)命令的封裝.命令模式把發(fā)出命令的責(zé)任和執(zhí)行命令的責(zé)任分割開(kāi),委派給不同的對(duì)象.該模式的示意類(lèi)圖如下: 下面是一個(gè)Command模式的例子(模仿<Java與模式>中的例子). 現(xiàn)有一個(gè)錄音機(jī)(AudioPlayer),他有播放(Play),到帶(Rewind)和停止(Stop)三個(gè)功能,利用Command模式實(shí)現(xiàn)中,錄音機(jī)(AudioPlayer)則為Receiver對(duì)象,將錄音機(jī)的鍵盤(pán)作為Invoker對(duì)象,因?yàn)榭蛻羰峭ㄟ^(guò)他去執(zhí)行播放,倒帶,停止的功能(命令). 首先:定義錄音機(jī)對(duì)象 /**//// <summary> /// 錄音機(jī)對(duì)象,該對(duì)象充當(dāng)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"); } } 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 } /**//// <summary> /// 錄音機(jī)鍵盤(pán)對(duì)象,該對(duì)象充當(dāng)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對(duì)象 /**//*各個(gè)具體命令對(duì)象*/ AbstractCommand playCmd = new PlayCommand(player); AbstractCommand stopCmd = new StopCommand(player); AbstractCommand rewindCmd = new RewindCommand(player); KeyPad pad = new KeyPad(playCmd,stopCmd,rewindCmd); //定義invoker對(duì)象 /**//*通過(guò)invoker進(jìn)行命令的執(zhí)行*/ pad.Play(); pad.Rewind(); pad.Stop(); |
|
來(lái)自: qzg589 > 《我的圖書(shū)館》