Last active
February 6, 2024 09:39
-
-
Save ozaki-shinya/3b70bd35ae0e21d9c99fb2846532a772 to your computer and use it in GitHub Desktop.
Unity用サービスロケーター (ServiceLocator)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
/// <summary> | |
/// サービスロケーター | |
/// </summary> | |
public static class Locator | |
{ | |
/// <summary> | |
/// 単一インスタンス用ディクショナリー | |
/// </summary> | |
private static Dictionary<Type, object> _instanceDict = new Dictionary<Type, object>(); | |
/// <summary> | |
/// 都度インスタンス生成用ディクショナリー | |
/// </summary> | |
private static Dictionary<Type, Type> _typeDict = new Dictionary<Type, Type>(); | |
/// <summary> | |
/// 単一インスタンスを登録する | |
/// 呼び直すと上書き登録する | |
/// </summary> | |
/// <typeparam name="T">型</typeparam> | |
/// <param name="instance">インスタンス</param> | |
public static void Register<T>(T instance) where T : class | |
{ | |
_instanceDict[typeof(T)] = instance; | |
} | |
/// <summary> | |
/// 型を登録する | |
/// このメソッドで登録するとResolveしたときに都度インスタンス生成する | |
/// </summary> | |
/// <typeparam name="TContract">抽象型</typeparam> | |
/// <typeparam name="TConcrete">具現型</typeparam> | |
public static void Register<TContract, TConcrete>() where TContract : class | |
{ | |
_typeDict[typeof(TContract)] = typeof(TConcrete); | |
} | |
/// <summary> | |
/// 型を指定して登録されているインスタンスを取得する | |
/// </summary> | |
/// <typeparam name="T">型</typeparam> | |
/// <returns>インスタンス</returns> | |
public static T Resolve<T>() where T : class | |
{ | |
T instance = default; | |
Type type = typeof(T); | |
if (_instanceDict.ContainsKey(type)) | |
{ | |
// 事前に生成された単一インスタンスを返す | |
instance = _instanceDict[type] as T; | |
return instance; | |
} | |
if (_typeDict.ContainsKey(type)) | |
{ | |
// インスタンスを生成して返す | |
instance = Activator.CreateInstance(_typeDict[type]) as T; | |
return instance; | |
} | |
if (instance == null) | |
{ | |
Debug.LogWarning($"Locator: {typeof(T).Name} not found."); | |
} | |
return instance; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
こちらの記事で使い方を紹介しています
[Qiita] Unityでサービスロケーター(ServiceLocator)を活用する