概述
命令模式也是一种行为型的设计模式,其主要目的是将发送者和接受者解耦,发送者不需要知道接受者具体的内容,只需要发送出命令就行,调用对应的方法。其中主要的组成部分是,命令接口,具体的各种命令,命令发送者,命令接受者,发送者发送具体的命令给接受者,接受者处理对应的逻辑,举例如下
例子:在常见得2D游戏中,玩家常见的操作有前进后退跳跃的命令,实现这个玩家控制器。
命令模式
using System.Numerics;internal class Program
{private static void Main(string[] args){Player player = new Player();//创建玩家ICommand forword = new Forward(player);//创建玩家操作ICommand retreat = new Retreat(player);ICommand jump = new Jump(player);PlayerControl playerControl = new PlayerControl();//创建玩家控制器playerControl.PlayerCommand(forword);//前进命名playerControl.Execute();playerControl.PlayerCommand(retreat);//后退命令playerControl.Execute();}public interface ICommand//命令接口{void Operate();}public class Forward : ICommand//前进操作{private readonly Player _player;public Forward(Player player){_player = player;}public void Operate(){_player.PlayerForword();}}public class Retreat : ICommand//后退操作{private readonly Player _player;public Retreat(Player player){_player = player;}public void Operate(){_player.PlayerRetreat();}}public class Jump : ICommand//跳跃操作{private readonly Player _player;public Jump(Player player){_player = player;}public void Operate(){_player.PlayerJump();}}public class Player//玩家{public void PlayerForword(){Console.WriteLine("Player Forword Operate!");}public void PlayerRetreat(){Console.WriteLine("Player Retreat Operate!");}public void PlayerJump(){Console.WriteLine("Player Jump Operate!");}}public class PlayerControl//玩家控制器{private ICommand _command;public void PlayerCommand(ICommand command){_command = command;}public void Execute(){_command.Operate();}}
}
执行结果
Player Forword Operate!
Player Retreat Operate!