Kiến trúc: Mẫu Service Locator
C# Code
using UnityEngine;
using System.Collections.Generic;
// 1. Service Locator: Một class static để đăng ký và lấy các services
public static class ServiceLocator
{
private static readonly Dictionary<System.Type, object> services = new Dictionary<System.Type, object>();
public static void Register<T>(T service) where T : class
{
var type = typeof(T);
if (services.ContainsKey(type))
{
Debug.LogWarning($"Service of type {type} is already registered.");
return;
}
services[type] = service;
Debug.Log($"Service registered: {type.Name}");
}
public static T Get<T>() where T : class
{
var type = typeof(T);
if (!services.TryGetValue(type, out var service))
{
Debug.LogError($"Service of type {type} not found.");
return null;
}
return (T)service;
}
public static void Unregister<T>() where T : class {
services.Remove(typeof(T));
}
}
// 2. Một interface cho service (ví dụ: IAudioManager)
public interface IAudioManager {
void PlaySound(string soundName);
}
// 3. Class triển khai service
public class AudioManager : MonoBehaviour, IAudioManager
{
void Awake()
{
// Đăng ký chính nó vào Service Locator
ServiceLocator.Register<IAudioManager>(this);
}
void OnDestroy() {
ServiceLocator.Unregister<IAudioManager>();
}
public void PlaySound(string soundName) {
Debug.Log("Playing sound: " + soundName);
}
}
// 4. Một class khác sử dụng service
public class Player : MonoBehaviour
{
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
// Lấy AudioManager từ Service Locator và sử dụng
IAudioManager audioManager = ServiceLocator.Get<IAudioManager>();
audioManager?.PlaySound("Player_Jump");
}
}
}Triển khai mẫu Service Locator, một cách đơn giản để các phần khác nhau của game có thể truy cập vào các hệ thống toàn cục (services) như AudioManager, GameManager mà không cần tham chiếu trực tiếp.