Unity에서 사용할 factory pattern을 구현하던 도중 Unity3d College라는 채널에 올라온 영상을 보고 구현.
채널 자체는 기본적인 내용들이 들어가있어서 둘러보기 괜찮을 것 같다.
코드는 영상과 같진 않고, 조금씩만 바꿨다.
public interface IHaveStringIdentifier
{
string Identifier { get; }
}
public interface IBuffBehavior : IHaveStringIdentifier
{
void DoBuffBehavior();
}
public sealed class BonusHPBuff : IBuffBehavior
{
public string Identifier => BuffBehaviorType.BonusHp.ToString();
public void DoBuffBehavior() { Console.WriteLine("Do Bonus to HP!"); }
}
public sealed class BonusDamageBuff : IBuffBehavior
{
public string Identifier => BuffBehaviorType.BonusDamage.ToString();
public void DoBuffBehavior() { Console.WriteLine("Do Bonus to Damage!"); }
}
public static class BuffBehaviorFactory
{
private static Dictionary<string, Type> _behaviorTypes = null;
private static bool IsInit => _behaviorTypes != null;
public static void InitializeFactory()
{
if (IsInit) return;
var buffTypes = Assembly.GetAssembly(typeof(IBuffBehavior)).GetTypes()
.Where(x => (typeof(IBuffBehavior).IsAssignableFrom(x) && x.IsAbstract() == false));
_behaviorTypes = new Dictionary<string, Type>();
foreach (var type in buffTypes)
{
var templateObject = Activator.CreateInstance(type) as IBuffBehavior;
_behaviorTypes.Add(templateObject.Identifier, type);
}
}
public static IBuffBehavior MakeBehavior(BuffBehaviorType behaviorEnumType)
{
var stringIdentifier = behaviorEnumType.ToString();
if (_behaviorTypes.ContainsKey(stringIdentifier) == false)
return null;
var behaviorType = _behaviorTypes[stringIdentifier];
return Activator.CreateInstance(type) as IBuffBehavior;
}
}
'프로그래밍 > Unity' 카테고리의 다른 글
Unity - StateMachineBehaviour를 얻는법 (0) | 2020.07.07 |
---|---|
[Unite Seoul 2019] 양진석 - 효과적인 에셋 관리를 위한 어드레서블 에셋 시스템 소개 (0) | 2020.05.14 |
UnityEvent vs C# Event : 무엇을 쓸까? (1) | 2020.03.13 |
Unity SceneManager.sceneLoaded (0) | 2020.03.12 |
유니티 테스트 러너(Unity Test Runner) (0) | 2020.03.01 |