comparison of the Event Bus, Mediator, and Singleton design patterns in C# with Unity

comparison of the Event Bus, Mediator, and Singleton design patterns in C# with Unity

Event Bus:

  • Allows objects to subscribe to and publish events
  • Decouples the publisher from the subscriber
  • Useful for implementing the Observer pattern
  • Example in Unity: Use UnityEvent to create custom events that can be subscribed to by multiple components

public class EventBusExample : MonoBehaviour
{
    public UnityEvent<int> OnValueChanged;

    private int _value;
    public int Value
    {
        get { return _value; }
        set
        {
            _value = value;
            OnValueChanged.Invoke(value); // Publish event
        }
    }
}        

Mediator:

  • Centralizes communication between objects
  • Defines a unified interface for interaction
  • Reduces coupling between components
  • Example in Unity: Use a ScriptableObject as a centralized Mediator to coordinate between game objects


public class MediatorExample : ScriptableObject
{
    public void PerformAction(GameObject obj, string action)
    {
        switch (action)
        {
            case "Move":
                obj.transform.Translate(Vector3.forward);
                break;
            case "Shoot":
                obj.GetComponent<Weapon>().Shoot();
                break;
        }
    }
}        

Singleton:

  • Ensures a class has only one instance
  • Provides a global point of access to that instance
  • Useful for managing global state or resources
  • Example in Unity: Use a Singleton pattern to manage a game-wide settings object

public class SettingsSingleton : MonoBehaviour
{
    private static SettingsSingleton _instance;
    public static SettingsSingleton Instance
    {
        get
        {
            if (_instance == null)
            {
                _instance = FindObjectOfType<SettingsSingleton>();
                if (_instance == null)
                {
                    GameObject obj = new GameObject("SettingsSingleton");
                    _instance = obj.AddComponent<SettingsSingleton>();
                }
            }
            return _instance;
        }
    }

    public float MasterVolume = 1f;
    public float MusicVolume = 0.8f;
    public float SfxVolume = 0.9f;
}        

Conclusion

These design patterns offer different approaches to managing communication and state in your Unity projects. The Event Bus decouples publishers and subscribers, the Mediator centralizes coordination, and the Singleton ensures global access to a single instance. Choosing the right pattern depends on the specific requirements of your application.


要查看或添加评论,请登录

社区洞察

其他会员也浏览了