欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 时评 > 设计模式-命令模式

设计模式-命令模式

2024/10/24 16:24:09 来源:https://blog.csdn.net/qq_58870988/article/details/141366027  浏览:    关键词:设计模式-命令模式

概述

命令模式也是一种行为型设计模式其主要目的是将发送者和接受者解耦,发送者不需要知道接受者具体的内容,只需要发送出命令就行,调用对应的方法。其中主要的组成部分是,命令接口,具体的各种命令,命令发送者,命令接受者,发送者发送具体的命令给接受者,接受者处理对应的逻辑,举例如下


例子:在常见得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!

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com