چیست؟
پترن Strategy خانوادهای از الگوریتمهای جایگزینپذیر را از کلاسی که از آنها استفاده میکند بیرون میکشد. استفادهکننده (یعنی Context) ارجاعی به یک interface مثل IAttackStrategy نگه میدارد و Attack(target) را صدا میزند. اصلاً هم نمیداند پشت آن یک شمشیر است، یک کمان یا یک گلولهٔ آتش.
هر Strategy مشخص (MeleeAttack، RangedAttack، MagicAttack) برد، آسیب و افکتهای خودش را در خودش نگه میدارد. پس اگر بخواهی شیوهٔ جنگیدن کاراکتر را عوض کنی، فقط یک شیء دیگر در یک فیلد میگذاری؛ لازم نیست یک زنجیرهٔ if/else را که مدام بلندتر میشود ویرایش کنی.
Strategyهای این مثال کلاسهای سادهٔ C# هستند، ولی در پروژههای واقعی اغلب ScriptableObject میشوند. طراح یک asset به نام «عصای آتش» میسازد، اعدادش را در Inspector تنظیم میکند و آن را در اسلات سلاح میکشد. برداشتن یک سلاح جدید در زمان اجرا هم فقط یعنی عوض شدن یک ارجاع.
کِی به کار میآید؟
وقتی یک رفتار چند نسخه دارد و میخواهی در زمان اجرا یکی را انتخاب کنی یا عوضش کنی، سراغش برو: سلاحها، قانونهای هدفگیری AI، حالتهای حرکت، منحنیهای سختی و heuristicهای مسیریابی.
هر وقت متدی با switch (weaponType) شروع میشود و هر شاخهاش حجم قابلتوجهی دارد، یک refactor خوب است. هر شاخه به کلاسی با یک مسئولیت واحد تبدیل میشود.
اگر فقط دو نسخهٔ خیلی کوچک داری که در زمان اجرا هم عوض نمیشوند، یک پارامتر ساده یا یک delegate (Func<float, float>) از یک interface کامل و چند کلاس سبکتر است.
دموی تعاملی
دکمهها را بزن و ببین اشیا چطور با هم کار میکنند. کنسول همان چیزی را نشان میدهد که کد C# پایین صفحه لاگ میکند.
کد
using UnityEngine;
namespace Patterns.Behavioral.Strategy
{
/// <summary>
/// Client: picks strategies at runtime and tells the attacker to
/// attack. Swapping weapons is just reassigning a reference.
/// </summary>
public class StrategyTester : MonoBehaviour
{
[SerializeField] private Attacker attacker;
[SerializeField] private Transform dummy; // must have an IDamageable component
[SerializeField] private Rigidbody arrowPrefab;
private IAttackStrategy melee;
private IAttackStrategy ranged;
private IAttackStrategy magic;
private void Awake()
{
melee = new MeleeAttack();
ranged = new RangedAttack(arrowPrefab);
magic = new MagicAttack();
attacker.SetStrategy(melee);
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.Alpha1)) attacker.SetStrategy(melee);
if (Input.GetKeyDown(KeyCode.Alpha2)) attacker.SetStrategy(ranged);
if (Input.GetKeyDown(KeyCode.Alpha3)) attacker.SetStrategy(magic);
if (Input.GetKeyDown(KeyCode.Space) && dummy.TryGetComponent(out IDamageable target))
attacker.AttackTarget(target);
}
}
}using UnityEngine;
namespace Patterns.Behavioral.Strategy
{
/// <summary>
/// The strategy contract. The attacker calls this without knowing
/// which concrete attack it is holding.
/// </summary>
public interface IAttackStrategy
{
string Name { get; }
float Range { get; }
void Attack(Transform attacker, IDamageable target);
}
/// <summary>Anything that can be hit.</summary>
public interface IDamageable
{
Transform Transform { get; }
void TakeDamage(int amount);
}
}using UnityEngine;
namespace Patterns.Behavioral.Strategy
{
/// <summary>Close-range, high-damage swing.</summary>
public class MeleeAttack : IAttackStrategy
{
public string Name => "Melee";
public float Range => 1.5f;
public void Attack(Transform attacker, IDamageable target)
{
target.TakeDamage(25);
}
}
/// <summary>Launches an arrow toward the target from a distance.</summary>
public class RangedAttack : IAttackStrategy
{
private readonly Rigidbody arrowPrefab;
public RangedAttack(Rigidbody arrowPrefab) => this.arrowPrefab = arrowPrefab;
public string Name => "Ranged";
public float Range => 15f;
public void Attack(Transform attacker, IDamageable target)
{
Vector3 direction = (target.Transform.position - attacker.position).normalized;
Rigidbody arrow = Object.Instantiate(arrowPrefab, attacker.position, Quaternion.LookRotation(direction));
arrow.linearVelocity = direction * 30f;
Object.Destroy(arrow.gameObject, 2f);
target.TakeDamage(12); // hitscan damage; the arrow is visual
}
}
/// <summary>Damages the target and everything near it.</summary>
public class MagicAttack : IAttackStrategy
{
private const float BlastRadius = 3f;
public string Name => "Magic";
public float Range => 10f;
public void Attack(Transform attacker, IDamageable target)
{
Collider[] hits = Physics.OverlapSphere(target.Transform.position, BlastRadius);
foreach (Collider hit in hits)
{
if (hit.TryGetComponent(out IDamageable victim))
victim.TakeDamage(18);
}
}
}
}using UnityEngine;
namespace Patterns.Behavioral.Strategy
{
/// <summary>
/// Context. Holds one attack strategy and delegates to it.
/// It never checks which kind of attack it is.
/// </summary>
public class Attacker : MonoBehaviour
{
private IAttackStrategy strategy;
public IAttackStrategy Strategy => strategy;
public void SetStrategy(IAttackStrategy next)
{
if (next == null || next == strategy) return;
strategy = next;
Debug.Log($"{name} switched to {strategy.Name}");
}
public void AttackTarget(IDamageable target)
{
if (strategy == null) return;
float distance = Vector3.Distance(transform.position, target.Transform.position);
if (distance > strategy.Range)
{
Debug.Log($"{strategy.Name}: target out of range ({distance:0.0}m)");
return;
}
strategy.Attack(transform, target);
}
}
}قبل و بعد از پترن
یک موقعیت واقعی: مهاجمی که روی نوع سلاحش switch میزند. اینجا کد بدون پترن، نسخهٔ بازنویسیشده و diff دقیق بینشان را میبینی.
! مشکل کجاست؟
Attacker یک enum از نوع AttackType دارد. AttackTarget با یک switch برد را انتخاب میکند و با switch دوم منطق حملهٔ نزدیک، دوربرد یا جادویی را همانجا اجرا میکند؛ یک arrowPrefab هم با خودش دارد که فقط یکی از شاخهها از آن استفاده میکند.
اضافه کردن یک سلاح یعنی دست بردن در هر دو switch، آن هم در کلاسی که همهٔ دشمنها از آن استفاده میکنند، و خیلی راحت یکی را عوض میکنی و دیگری یادت میرود. این سه حمله را نمیشود جدا جدا تنظیم یا تست کرد، و طراحها بدون برنامهنویس نمیتوانند نسخهٔ تازهای اضافه کنند.
✓ چه چیزی عوض شد؟
- enum
AttackType، هر دو switch و فیلدarrowPrefabاز مهاجم حذف شدند. - حالا
AttackTargetبرد را ازRangeدرIAttackStrategyفعلی میپرسد و بعدstrategy.Attack(transform, target)را صدا میزند. - هر حمله حالا در کلاس خودش است (
MeleeAttack،RangedAttack،MagicAttack)، همراه با دادههای خودش مثل prefab تیر. - متد
SetStrategyرفتار را در زمان اجرا عوض میکند، و هر سلاح تازه یک کلاس تازه است بدون هیچ تغییری درAttacker.
using UnityEngine;
namespace Patterns.Behavioral.Strategy
{
/// <summary>
/// Without Strategy: the attacker knows every kind of attack and
/// picks one with a switch on an enum.
/// </summary>
public class Attacker : MonoBehaviour
{
public enum AttackType { Melee, Ranged, Magic }
[SerializeField] private AttackType attackType = AttackType.Melee;
[SerializeField] private Rigidbody arrowPrefab; // only used by Ranged
public void SetAttackType(AttackType next) => attackType = next;
public void AttackTarget(IDamageable target)
{
float range = attackType switch
{
AttackType.Melee => 1.5f,
AttackType.Ranged => 15f,
_ => 10f,
};
float distance = Vector3.Distance(transform.position, target.Transform.position);
if (distance > range)
{
Debug.Log($"{attackType}: target out of range ({distance:0.0}m)");
return;
}
switch (attackType)
{
case AttackType.Melee:
target.TakeDamage(25);
break;
case AttackType.Ranged:
Vector3 direction = (target.Transform.position - transform.position).normalized;
Rigidbody arrow = Instantiate(arrowPrefab, transform.position, Quaternion.LookRotation(direction));
arrow.linearVelocity = direction * 30f;
Destroy(arrow.gameObject, 2f);
target.TakeDamage(12);
break;
case AttackType.Magic:
foreach (Collider hit in Physics.OverlapSphere(target.Transform.position, 3f))
{
if (hit.TryGetComponent(out IDamageable victim))
victim.TakeDamage(18);
}
break;
}
}
}
}using UnityEngine;
namespace Patterns.Behavioral.Strategy
{
/// <summary>
/// With Strategy: the attacker holds one IAttackStrategy and delegates
/// to it. Each attack's range and logic live in its own class.
/// </summary>
public class Attacker : MonoBehaviour
{
private IAttackStrategy strategy;
public void SetStrategy(IAttackStrategy next) => strategy = next;
public void AttackTarget(IDamageable target)
{
if (strategy == null) return;
float distance = Vector3.Distance(transform.position, target.Transform.position);
if (distance > strategy.Range)
{
Debug.Log($"{strategy.Name}: target out of range ({distance:0.0}m)");
return;
}
strategy.Attack(transform, target);
}
}
}مزایا و معایب
+ مزایا
- الگوریتمها در زمان اجرا قابل جایگزینی هستند، بدون دست زدن به Context.
- نسخههای جدید به شکل کلاسهای جدید اضافه میشوند و کد موجود و تستشده دستنخورده میماند.
- هر Strategy کوچک و مستقل است، پس تنظیم کردن و unit test نوشتن برایش راحت است.
− معایب
- تعداد typeهایی که باید مدیریت کنی بیشتر میشود؛ تفاوتهای جزئی شاید ارزش یک کلاس جدا را نداشته باشند.
- فراخوانیکنندهها باید آنقدر دربارهٔ Strategyها بدانند که بتوانند گزینهٔ درست را انتخاب کنند.
- اگر نیازهای دادهٔ Strategyها خیلی با هم فرق کند، ممکن است مجبور شوی یک interface شلوغ و همهکاره بسازی که باید جواب نیاز همه را با هم بدهد.
چند نکتهٔ کاربردی
- ۰۱Strategyها را assetهای
ScriptableObjectکن تا طراحها بتوانند بدون تغییر کد نسخههای جدید بسازند و بالانسشان کنند. - ۰۲تا جای ممکن Strategyها را بدون state نگه دار تا یک asset بتواند بین چندین مهاجم مشترک باشد.
- ۰۳بهجای اینکه به Strategyها ارجاع به همه چیز بدهی، یک context کوچک (transform مهاجم، هدف، آمار) به متد بفرست.
- ۰۴Strategy و State در کد شبیه هماند. فرقشان در نیت است: Strategy از بیرون انتخاب میشود، ولی stateها خودشان انتقالهایشان را راه میاندازند.
- ۰۵برای رفتارهای یکباره، یک delegate یا lambda در C# یک Strategy سبک و کاملاً معتبر است.