命令模式是否足够有效,它的具体好处是什么?

时间:2016-07-25 13:51:21

标签: c# oop design-patterns unity3d command-pattern

所以今天我正在学习和实现命令模式来处理对象的输入和移动。

所以我的问题是:

  1. 我是否正确执行命令模式或是否需要修改它?如果是这样,有人可以举一些例子来改进它。
  2. 我知道它可以提高代码的可重用性。但是当我只使用一个简单的MovementScript.cs到我的游戏对象组件时它会有什么不同?是不是只是相同而且花费更少的时间来编写而不是制作整个命令模式?
  3. 我附加到游戏对象的那个只是InputHandler。这是我的代码,涉及移动一个对象:

    这是我的输入处理程序或据我所知的客户端

    public abstract class Command
    {
    
    //The Receiver of the command..
    protected IReceiver receiver = null;
    
    public Command(IReceiver receiver)
    {
        this.receiver = receiver;
    }
    
    public abstract void Execute();
    }
    

    命令抽象类

    public class Movement : IReceiver
    {
    public ACTION_LIST currentMoves;
    private GameObject theObject;
    private float acceleration;
    private float maxspeed;
    
    public Movement(GameObject theObject, float acceleration, float maxspeed)
    {
        this.theObject = theObject;
        this.acceleration = acceleration;
        this.maxspeed = maxspeed;
    }
    
    public void Action(ACTION_LIST moves)
    {
        if (moves == ACTION_LIST.MOVERIGHT)
            MoveRight(theObject);
        else if (moves == ACTION_LIST.MOVELEFT)
            MoveLeft(theObject);
    }
    
    public void MoveRight(GameObject obj)
    {
        obj.GetComponent<Rigidbody2D>().AddForce(new Vector2(acceleration, obj.GetComponent<Rigidbody2D>().velocity.y));
    }
    
    public void MoveLeft(GameObject obj)
    {
        obj.GetComponent<Rigidbody2D>().AddForce(new Vector2(-acceleration, obj.GetComponent<Rigidbody2D>().velocity.y));
    }
    
    }
    

    Receiver类(我实现了逻辑,即移动)

    public enum ACTION_LIST
    {
        MOVERIGHT,
        MOVELEFT
    }
    
    public interface IReceiver
    {
        void Action(ACTION_LIST moves);
    }
    

    接收器界面,让事情变得更轻松......

    public class MoveRight : Command
    {
    public MoveRight(IReceiver receiver):base(receiver)
    {
    
    }
    
    public override void Execute()
    {
        receiver.Action(ACTION_LIST.MOVERIGHT);
    }
    }
    

    具体命令。我只发布了一个动作..

    cp

1 个答案:

答案 0 :(得分:2)

我不同意Joe Blow和其他人说Unity是一堆脚本而不是OOP。我使用带有单个入口点的主脚本并动态创建所有对象和组件。我甚至使用接口,模拟和单元测试。

因此,使用命令模式是可以的。但是我没有理由在你的情况下使用它。 命令模式可能非常方便,以防您需要一堆命令才能Do()Undo()您的命令(编辑器,策略游戏)。请在此处阅读更多内容:http://gameprogrammingpatterns.com/command.html