چیست؟
Model–View–Presenter هر صفحه را به سه نقش تقسیم میکند. Model state و قوانین را به شکل C# ساده نگه میدارد (طلا، آیتمها، «پولم به این میرسد؟»). View یک MonoBehaviour است که فقط Buttonها و TMP_Textها را در اختیار دارد و کار دیگری نمیکند. Presenter این وسط مینشیند و تنها بخشی است که با هر دو حرف میزند.
جریان داده یک حلقه است. کلیک در View یک event مثل BuyClicked میفرستد؛ Presenter آن را به model.TryBuy(potion) تبدیل میکند؛ Model تغییر میکند و Changed را اعلام میکند؛ Presenter state جدید را میخواند و view.Render(gold, items, canBuy) را صدا میزند. View هیچوقت ارجاعی به Model ندارد.
فرض کن یک صفحهٔ فروشگاه داری. قیمتهای فروشنده، کیف پول بازیکن و قوانین inventory همه در یک InventoryModel هستند که بدون هیچ sceneی میتوانی unit testش کنی. در همین حال میشود InventoryView را از uGUI به UI Toolkit برد، بیآنکه حتی به یک قانون بازی دست بزنی.
کِی به کار میآید؟
برای هر UI که منطق واقعی پشتش هست از آن استفاده کن: فروشگاه، inventory، صفحهٔ کرفتینگ، منوی تنظیمات با اعتبارسنجی.
جایی ارزشش را نشان میدهد که بخواهی برای قوانین UI تست خودکار داشته باشی، یا طراحها مدام چیدمان صفحهها را عوض کنند و نخواهی این تغییرها کد گیمپلی را خراب کنند.
برای یک منوی pause ساده با سه دکمه که فقط SceneManager.LoadScene را صدا میزنند، MVP تشریفات اضافه است. تا وقتی state و قانونی در کار نیست، ساده نگهش دار.
دموی تعاملی
دکمهها را بزن و ببین اشیا چطور با هم کار میکنند. کنسول همان چیزی را نشان میدهد که کد C# پایین صفحه لاگ میکند.
کد
using UnityEngine;
namespace Patterns.Architectural.MVP
{
/// <summary>
/// Builds the triad for the shop screen: creates the Model, finds the
/// View in the scene and hands both to a new Presenter.
/// </summary>
public class InventoryBootstrap : MonoBehaviour
{
[SerializeField] private InventoryView view;
[SerializeField] private int startingGold = 50;
private InventoryPresenter presenter;
private void Start()
{
var model = new InventoryModel(startingGold);
presenter = new InventoryPresenter(model, view);
}
private void OnDestroy()
{
presenter?.Dispose();
presenter = null;
}
}
}using System;
using System.Collections.Generic;
namespace Patterns.Architectural.MVP
{
/// <summary>
/// The Model: pure C#, no UnityEngine dependency. Owns state and rules
/// and announces every change through an event.
/// </summary>
public class InventoryModel
{
private readonly List<string> items = new();
public int Gold { get; private set; }
public IReadOnlyList<string> Items => items;
public int Capacity { get; } = 6;
public event Action Changed;
public InventoryModel(int startingGold) => Gold = startingGold;
public void AddGold(int amount)
{
if (amount <= 0) return;
Gold += amount;
Changed?.Invoke();
}
public bool TryBuy(string itemId, int price)
{
if (Gold < price || items.Count >= Capacity)
return false;
Gold -= price;
items.Add(itemId);
Changed?.Invoke();
return true;
}
}
}using System;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
namespace Patterns.Architectural.MVP
{
/// <summary>
/// The View: owns UI references, forwards clicks as events and draws
/// whatever it is told to. It never sees the Model.
/// </summary>
public class InventoryView : MonoBehaviour
{
[SerializeField] private Button buyButton;
[SerializeField] private Button addGoldButton;
[SerializeField] private TMP_Text goldLabel;
[SerializeField] private TMP_Text itemsLabel;
[SerializeField] private TMP_Text feedbackLabel;
public event Action BuyClicked;
public event Action AddGoldClicked;
private void OnEnable()
{
buyButton.onClick.AddListener(OnBuy);
addGoldButton.onClick.AddListener(OnAddGold);
}
private void OnDisable()
{
buyButton.onClick.RemoveListener(OnBuy);
addGoldButton.onClick.RemoveListener(OnAddGold);
}
private void OnBuy() => BuyClicked?.Invoke();
private void OnAddGold() => AddGoldClicked?.Invoke();
public void Render(int gold, IReadOnlyList<string> items, bool canBuy)
{
goldLabel.text = $"{gold} g";
itemsLabel.text = items.Count == 0 ? "(empty)" : string.Join(", ", items);
buyButton.interactable = canBuy;
}
public void ShowFeedback(string message) => feedbackLabel.text = message;
}
}using System;
namespace Patterns.Architectural.MVP
{
/// <summary>
/// The Presenter: translates View events into Model calls and Model
/// changes into View renders. The only class that knows both sides.
/// </summary>
public class InventoryPresenter : IDisposable
{
private const string PotionId = "Potion";
private const int PotionPrice = 30;
private const int GoldPerClick = 25;
private readonly InventoryModel model;
private readonly InventoryView view;
public InventoryPresenter(InventoryModel model, InventoryView view)
{
this.model = model;
this.view = view;
view.BuyClicked += HandleBuy;
view.AddGoldClicked += HandleAddGold;
model.Changed += Refresh;
Refresh();
}
private void HandleBuy()
{
if (!model.TryBuy(PotionId, PotionPrice))
view.ShowFeedback("Not enough gold or bag is full.");
}
private void HandleAddGold() => model.AddGold(GoldPerClick);
private void Refresh()
{
bool canBuy = model.Gold >= PotionPrice && model.Items.Count < model.Capacity;
view.Render(model.Gold, model.Items, canBuy);
}
public void Dispose()
{
view.BuyClicked -= HandleBuy;
view.AddGoldClicked -= HandleAddGold;
model.Changed -= Refresh;
}
}
}قبل و بعد از پترن
یک موقعیت واقعی: صفحهٔ فروشگاهی که طلای خودش را خودش نگه میدارد. اینجا کد بدون پترن، نسخهٔ بازنویسیشده و diff دقیق بینشان را میبینی.
! مشکل کجاست؟
کلاس InventoryView طلا، لیست آیتمها، قیمت معجون و ظرفیت کیف را نگه میدارد، و OnBuy هم قوانین را چک میکند و هم مستقیم در برچسبهای TMP_Text مینویسد.
برای تست کردن «پولم به معجون میرسد؟» به یک scene، یک Canvas و پنج ارجاع وصلشده نیاز داری. همان قانون «پول کافی و جای خالی» هم در OnBuy آمده و هم در Render، و بردن این صفحه به UI Toolkit یعنی بازنویسی منطق فروشگاه همراه با layout.
✓ چه چیزی عوض شد؟
- طلا، آیتمها،
Capacityو قانون خرید بهInventoryModelمنتقل شدند، که یک کلاس C# ساده است وChangedرا اعلام میکند؛startingGoldهم بهInventoryBootstrapرفت. - قیمتها و رسیدگی به کلیکها به
InventoryPresenterرفتند؛ Presenter eventBuyClickedرا بهmodel.TryBuyتبدیل میکند و بعد از هر تغییرview.Renderرا صدا میزند. - حالا View فقط فیلدهای UI خودش را دارد:
OnBuyوOnAddGoldفقط event میفرستند وRender(gold, items, canBuy)هر چه به آن بدهند نمایش میدهد. - دیگر View هیچ قیمت یا ظرفیتی نمیشناسد؛ پس بردن صفحه به UI Toolkit یعنی فقط نوشتن یک View تازه.
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
namespace Patterns.Architectural.MVP
{
/// <summary>
/// Without MVP: one MonoBehaviour owns the gold, the bag, the shop
/// rules and every label. None of it can be tested without a scene.
/// </summary>
public class InventoryView : MonoBehaviour
{
[SerializeField] private Button buyButton;
[SerializeField] private Button addGoldButton;
[SerializeField] private TMP_Text goldLabel;
[SerializeField] private TMP_Text itemsLabel;
[SerializeField] private TMP_Text feedbackLabel;
[SerializeField] private int startingGold = 50;
private const string PotionId = "Potion";
private const int PotionPrice = 30;
private const int GoldPerClick = 25;
private const int Capacity = 6;
private readonly List<string> items = new();
private int gold;
private void Awake() => gold = startingGold;
private void OnEnable()
{
buyButton.onClick.AddListener(OnBuy);
addGoldButton.onClick.AddListener(OnAddGold);
Render();
}
private void OnDisable()
{
buyButton.onClick.RemoveListener(OnBuy);
addGoldButton.onClick.RemoveListener(OnAddGold);
}
private void OnBuy()
{
if (gold < PotionPrice || items.Count >= Capacity)
{
feedbackLabel.text = "Not enough gold or bag is full.";
return;
}
gold -= PotionPrice;
items.Add(PotionId);
Render();
}
private void OnAddGold()
{
gold += GoldPerClick;
Render();
}
private void Render()
{
goldLabel.text = $"{gold} g";
itemsLabel.text = items.Count == 0 ? "(empty)" : string.Join(", ", items);
buyButton.interactable = gold >= PotionPrice && items.Count < Capacity;
}
}
}using System;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
namespace Patterns.Architectural.MVP
{
/// <summary>
/// With MVP: the view only owns UI references, forwards clicks as
/// events and draws whatever the Presenter tells it to.
/// </summary>
public class InventoryView : MonoBehaviour
{
[SerializeField] private Button buyButton;
[SerializeField] private Button addGoldButton;
[SerializeField] private TMP_Text goldLabel;
[SerializeField] private TMP_Text itemsLabel;
[SerializeField] private TMP_Text feedbackLabel;
public event Action BuyClicked;
public event Action AddGoldClicked;
private void OnEnable()
{
buyButton.onClick.AddListener(OnBuy);
addGoldButton.onClick.AddListener(OnAddGold);
}
private void OnDisable()
{
buyButton.onClick.RemoveListener(OnBuy);
addGoldButton.onClick.RemoveListener(OnAddGold);
}
private void OnBuy() => BuyClicked?.Invoke();
private void OnAddGold() => AddGoldClicked?.Invoke();
public void Render(int gold, IReadOnlyList<string> items, bool canBuy)
{
goldLabel.text = $"{gold} g";
itemsLabel.text = items.Count == 0 ? "(empty)" : string.Join(", ", items);
buyButton.interactable = canBuy;
}
public void ShowFeedback(string message) => feedbackLabel.text = message;
}
}مزایا و معایب
+ مزایا
- قوانین بازی در یک Model سادهٔ C# قرار میگیرند که در Edit Mode قابل تست است.
- Viewها نازک و قابل تعویض میشوند؛ برای رفتن از uGUI به UI Toolkit کافی است یک View جدید بنویسی.
- جریان داده صریح و یکطرفه است: از کلیک به Presenter، از آنجا به Model، بعد یک event، دوباره Presenter و در آخر View.
− معایب
- برای هر صفحه کلاسها و سیمکشی بیشتری لازم است تا حالتی که همهچیز در یک MonoBehaviour باشد.
- اگر هر دغدغهٔ صفحه را داخل Presenter بریزی، کمکم به یک «god object» باد کرده تبدیل میشود.
- اگر لغو اشتراک در
Disposeیادت برود، Presenterها بعد از بسته شدن صفحهشان زنده میمانند.
چند نکتهٔ کاربردی
- ۰۱برای View یک interface تعریف کن (
IInventoryView) تا بتوانی Presenter را با یک View جعلی تست کنی. - ۰۲بگذار View بهجای فیلدهای public از نوع
Button، eventهای C# (event Action BuyClicked) ارائه کند تا Presenter هیچوقت به نوعهای UI در Unity دست نزند. - ۰۳Presenter را
IDisposableکن و درDispose()همهٔ eventها را جدا کن. بعد آن را از اسکریپت bootstrap درOnDestroyصدا بزن. - ۰۴با هر تغییر، کل View را از روی state فعلی Model رندر کن، نه اینکه برچسبها را تکتک وصله کنی. اینطوری View همیشه هماهنگ میماند.
- ۰۵MVVM همراه با data binding در UI Toolkit پسرعموی نزدیک این پترن است. هر وقت خواستی کنترل صریحی روی هر بار بهروزرسانی داشته باشی، MVP را انتخاب کن.