Supercell.GUT/Supercell.GUT.Logic/Message/GUTMessageFactory.cs
BreadDEV ad23f95319 [v0.0.1] very early state server
only basic messages, wip.
2024-03-04 20:19:32 +07:00

40 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();
}
}