چیست؟
ایدهٔ Command این است که یک درخواست را به یک شیء مستقل تبدیل کنی. بهجای اینکه مستقیم unit.Move(Vector2Int.up) را صدا بزنی، یک MoveCommand میسازی که یادش میماند روی چه کسی و چه کاری باید انجام شود. بعد آن را به یک Invoker میدهی تا او تصمیم بگیرد کِی اجرا شود.
همهٔ Commandها یک interface کوچک و یکسان را پیاده میکنند که معمولاً فقط Execute() و Undo() دارد. چون Invoker فقط ICommand را میبیند، میتواند Commandها را در یک پشتهٔ تاریخچه بگذارد، برای Undo از آن بیرون بکشد و در پشتهٔ Redo قرار دهد. در تمام این مدت هم Invoker هیچ چیزی دربارهٔ حرکت، ساختوساز یا inventory نمیداند.
فرض کن یک بازی تاکتیکی روی صفحهٔ شطرنجی داری. هر قدمی که بازیکن روی یک خانه برمیدارد، یک MoveCommand میشود. Undo واحد را دقیقاً یک خانه عقب میبرد و Redo همان قدم را دوباره اجرا میکند. همین تاریخچه میتواند پایهٔ یک سیستم replay یا لاگ شبکهای ورودیهای بازیکن هم باشد.
کِی به کار میآید؟
هر وقت کارها باید برگشتپذیر باشند سراغش برو: ادیتور مرحله، بازیهای پازلی، بازیهای تاکتیکی نوبتی و هر چیزی که دکمهٔ Undo دارد.
برای تغییر کلیدهای ورودی، ضبط ماکرو، replay قطعی (deterministic) و فرستادن نیت بازیکن روی شبکه هم انتخاب طبیعی است. دلیلش ساده است: یک Command چیزی نیست جز مقداری داده بهعلاوهٔ یک متد.
برای کارهای پیوستهای که هر frame اجرا میشوند، مثل حرکت آنالوگ در یک بازی اکشن، سراغش نرو. اگر هر تیک Update را در یک شیء بستهبندی کنی، فقط garbage و پیچیدگی اضافه کردهای و سود چندانی نمیبری.
دموی تعاملی
دکمهها را بزن و ببین اشیا چطور با هم کار میکنند. کنسول همان چیزی را نشان میدهد که کد C# پایین صفحه لاگ میکند.
کد
using UnityEngine;
namespace Patterns.Behavioral.Command
{
/// <summary>
/// Client: turns key presses into command objects and hands them
/// to the invoker. It never moves the unit itself.
/// </summary>
public class InputHandler : MonoBehaviour
{
[SerializeField] private Transform unit;
[SerializeField] private RectInt board = new(0, 0, 5, 5);
private readonly CommandInvoker invoker = new();
private void Update()
{
if (Input.GetKeyDown(KeyCode.W)) Move(Vector2Int.up);
if (Input.GetKeyDown(KeyCode.S)) Move(Vector2Int.down);
if (Input.GetKeyDown(KeyCode.A)) Move(Vector2Int.left);
if (Input.GetKeyDown(KeyCode.D)) Move(Vector2Int.right);
if (Input.GetKeyDown(KeyCode.Z)) invoker.Undo();
if (Input.GetKeyDown(KeyCode.Y)) invoker.Redo();
}
private void Move(Vector2Int direction)
{
invoker.Execute(new MoveCommand(unit, direction, board));
}
}
}namespace Patterns.Behavioral.Command
{
/// <summary>
/// A single, reversible action. The invoker only knows this interface,
/// never the concrete work being done.
/// </summary>
public interface ICommand
{
/// <summary>Performs the action. Returns false if it could not run.</summary>
bool Execute();
/// <summary>Reverts exactly what Execute did.</summary>
void Undo();
}
}using UnityEngine;
namespace Patterns.Behavioral.Command
{
/// <summary>
/// Moves a unit one tile on a grid. Remembers where the unit started
/// so Undo can put it back precisely.
/// </summary>
public class MoveCommand : ICommand
{
private readonly Transform unit;
private readonly Vector2Int direction;
private readonly RectInt bounds;
private Vector3 previousPosition;
public MoveCommand(Transform unit, Vector2Int direction, RectInt bounds)
{
this.unit = unit;
this.direction = direction;
this.bounds = bounds;
}
public bool Execute()
{
Vector3 target = unit.position + new Vector3(direction.x, direction.y, 0f);
var cell = Vector2Int.RoundToInt(target);
if (!bounds.Contains(cell))
return false; // walking off the board is not allowed
previousPosition = unit.position;
unit.position = target;
return true;
}
public void Undo() => unit.position = previousPosition;
public override string ToString() => $"Move {direction}";
}
}using System.Collections.Generic;
using UnityEngine;
namespace Patterns.Behavioral.Command
{
/// <summary>
/// Runs commands and keeps the history needed for undo and redo.
/// It has no idea what any command actually does.
/// </summary>
public class CommandInvoker
{
private readonly Stack<ICommand> undoStack = new();
private readonly Stack<ICommand> redoStack = new();
public int UndoCount => undoStack.Count;
public int RedoCount => redoStack.Count;
public void Execute(ICommand command)
{
if (!command.Execute())
{
Debug.Log($"{command} blocked");
return;
}
undoStack.Push(command);
redoStack.Clear(); // a new action invalidates the old future
}
public void Undo()
{
if (undoStack.Count == 0) return;
ICommand command = undoStack.Pop();
command.Undo();
redoStack.Push(command);
}
public void Redo()
{
if (redoStack.Count == 0) return;
ICommand command = redoStack.Pop();
command.Execute();
undoStack.Push(command);
}
}
}قبل و بعد از پترن
یک موقعیت واقعی: یک input handler که تاریخچهٔ Undo را هم خودش نگه میدارد. اینجا کد بدون پترن، نسخهٔ بازنویسیشده و diff دقیق بینشان را میبینی.
! مشکل کجاست؟
InputHandler کلیدها را میخواند، مرز صفحه را چک میکند، واحد را جابهجا میکند و دو تاریخچهٔ Stack<Vector3> را هم نگه میدارد؛ همه در یک MonoBehaviour.
این تاریخچه فقط موقعیتها را میشناسد. پس اولین کاری که حرکت نیست (چرخیدن، گذاشتن یک کاشی، استفاده از آیتم) بدون یک جفت پشتهٔ دیگر قابل Undo نیست. اگر بخواهی همین واحد را از AI، replay یا شبکه حرکت بدهی، باید چک مرز و حسابوکتاب تاریخچه را آنجا هم کپی کنی.
✓ چه چیزی عوض شد؟
- پشتههای موقعیت و متدهای دستنویس
Undo/Redoحذف شدند؛ حالاCommandInvokerصاحب تاریخچهٔ همهٔ کارهاست. - حالا
Moveفقط یکMoveCommandمیسازد و آن را بهinvoker.Executeمیدهد. چک مرز و موقعیت قبلی داخل خود Command زندگی میکنند. - هر کار تازه یعنی یک کلاس
ICommandتازه. ورودی، AI یا سیستم replay همه میتوانند آن را از همان invoker رد کنند و Undo هم خودکار برایش کار میکند.
using System.Collections.Generic;
using UnityEngine;
namespace Patterns.Behavioral.Command
{
/// <summary>
/// Without Command: reading input, moving the unit and keeping the
/// undo history are all tangled together in one MonoBehaviour.
/// </summary>
public class InputHandler : MonoBehaviour
{
[SerializeField] private Transform unit;
[SerializeField] private RectInt board = new(0, 0, 5, 5);
// The history only stores positions, so moving is the only thing that can be undone.
private readonly Stack<Vector3> undoPositions = new();
private readonly Stack<Vector3> redoPositions = new();
private void Update()
{
if (Input.GetKeyDown(KeyCode.W)) Move(Vector2Int.up);
if (Input.GetKeyDown(KeyCode.S)) Move(Vector2Int.down);
if (Input.GetKeyDown(KeyCode.A)) Move(Vector2Int.left);
if (Input.GetKeyDown(KeyCode.D)) Move(Vector2Int.right);
if (Input.GetKeyDown(KeyCode.Z)) Undo();
if (Input.GetKeyDown(KeyCode.Y)) Redo();
}
private void Move(Vector2Int direction)
{
Vector3 target = unit.position + new Vector3(direction.x, direction.y, 0f);
if (!board.Contains(Vector2Int.RoundToInt(target)))
return;
undoPositions.Push(unit.position);
redoPositions.Clear();
unit.position = target;
}
private void Undo()
{
if (undoPositions.Count == 0) return;
redoPositions.Push(unit.position);
unit.position = undoPositions.Pop();
}
private void Redo()
{
if (redoPositions.Count == 0) return;
undoPositions.Push(unit.position);
unit.position = redoPositions.Pop();
}
}
}using UnityEngine;
namespace Patterns.Behavioral.Command
{
/// <summary>
/// With Command: input only creates command objects. The invoker owns
/// the history, and each command knows how to undo itself.
/// </summary>
public class InputHandler : MonoBehaviour
{
[SerializeField] private Transform unit;
[SerializeField] private RectInt board = new(0, 0, 5, 5);
private readonly CommandInvoker invoker = new();
private void Update()
{
if (Input.GetKeyDown(KeyCode.W)) Move(Vector2Int.up);
if (Input.GetKeyDown(KeyCode.S)) Move(Vector2Int.down);
if (Input.GetKeyDown(KeyCode.A)) Move(Vector2Int.left);
if (Input.GetKeyDown(KeyCode.D)) Move(Vector2Int.right);
if (Input.GetKeyDown(KeyCode.Z)) invoker.Undo();
if (Input.GetKeyDown(KeyCode.Y)) invoker.Redo();
}
private void Move(Vector2Int direction)
{
invoker.Execute(new MoveCommand(unit, direction, board));
}
}
}مزایا و معایب
+ مزایا
- Undo و Redo به دو پشته خلاصه میشوند، بهجای کد مخصوصی که همهجا پخش شده باشد.
- کدی که یک کار را راه میاندازد (ورودی، AI، UI) از کدی که آن را انجام میدهد جدا میشود.
- Commandها دادهاند: میتوانی آنها را در صف بگذاری، با تأخیر اجرا کنی، serialize کنی، لاگ بگیری یا دوباره پخش کنی.
− معایب
- هر کار کلاس مخصوص خودش را لازم دارد و این یعنی ممکن است کلی فایل کوچک داشته باشی.
- Undo باید state را دقیقاً برگرداند. برگرداندن درست Commandهایی که با فیزیک، اعداد تصادفی یا سیستمهای دیگر سروکار دارند سخت است.
- تاریخچههای طولانی به اشیا ارجاع نگه میدارند. پس شاید لازم باشد اندازهٔ پشته را محدود کنی یا وقتی اشیا از بین میروند آن را خالی کنی.
چند نکتهٔ کاربردی
- ۰۱هر بار که یک Command کاملاً جدید اجرا میشود، پشتهٔ Redo را خالی کن. وگرنه Redo ممکن است شاخهای از تاریخچه را اجرا کند که دیگر معنایی ندارد.
- ۰۲نتیجهٔ هر کار را داخل خود Command نگه دار (مثلاً موقعیت قبل از حرکت) تا
Undoمجبور نشود چیزی را دوباره حساب کند. - ۰۳قبل از اجرا اعتبارسنجی کن: اگر حرکتی مسدود است، اصلاً آن را در تاریخچه نگذار.
- ۰۴برای replay، شمارهٔ frame را کنار هر Command ثبت کن. بعد از یک state شروع مشخص، آنها را به ترتیب دوباره اجرا کن.
- ۰۵Commandها را کلاسهای سادهٔ C# نگه دار، نه MonoBehaviour، تا ساختنشان کمهزینه و تست کردنشان راحت باشد.