mirror of
https://github.com/thebreaddev/Supercell.GUT.git
synced 2024-09-20 09:07:47 +00:00
41 lines
1.3 KiB
C#
41 lines
1.3 KiB
C#
|
using Supercell.GUT.Logic.Message.Attributes;
|
|||
|
using Supercell.GUT.Titan.Message;
|
|||
|
using System.Collections.Immutable;
|
|||
|
using System.Reflection;
|
|||
|
|
|||
|
namespace Supercell.GUT.Logic.Message;
|
|||
|
|
|||
|
public class GUTMessageFactory : LogicMessageFactory
|
|||
|
{
|
|||
|
private readonly ImmutableDictionary<int, Type> s_types;
|
|||
|
|
|||
|
public GUTMessageFactory() : base()
|
|||
|
{
|
|||
|
this.s_types = CreateMessageMap();
|
|||
|
}
|
|||
|
|
|||
|
public override PiranhaMessage? CreateMessageByType(int messageType)
|
|||
|
{
|
|||
|
return this.s_types.TryGetValue(messageType, out Type? type) ?
|
|||
|
Activator.CreateInstance(type) as PiranhaMessage : null;
|
|||
|
}
|
|||
|
|
|||
|
private static ImmutableDictionary<int, Type> CreateMessageMap()
|
|||
|
{
|
|||
|
var builder = ImmutableDictionary.CreateBuilder<int, Type>();
|
|||
|
|
|||
|
IEnumerable<Type> types = Assembly.GetExecutingAssembly().GetTypes()
|
|||
|
.Where(t => t.GetCustomAttribute<VersionedMessageAttribute>() != null);
|
|||
|
|
|||
|
foreach (var type in types)
|
|||
|
{
|
|||
|
VersionedMessageAttribute attribute = type.GetCustomAttribute<VersionedMessageAttribute>()!;
|
|||
|
|
|||
|
if (!builder.TryAdd(attribute.MessageType, type))
|
|||
|
throw new Exception($"Piranha message with type {attribute.MessageType} defined twice!");
|
|||
|
}
|
|||
|
|
|||
|
return builder.ToImmutable();
|
|||
|
}
|
|||
|
}
|