我正在用c#设计一款游戏,我相信你会得到很多-但我的问题有点不同,因为我想围绕观察者模式设计一些东西,以我的理解-我找不到太多的信息。
我所有的包实现一个基本的接口,称为ippacket…当我收到一封某类邮包时,我正希望能引起一件大事。不需要使用大开关
我可能希望是这样的:
networkEvents。packetrecived +=[…]
谁能告诉我该怎么做?这样怎么样:
public interface IPacket
{
}
public class FooPacket: IPacket {}
public class PacketService
{
private static readonly ConcurrentDictionary<Type, Action<IPacket>> _Handlers = new ConcurrentDictionary<Type, Action<IPacket>>(new Dictionary<Type, Action<IPacket>>());
public static void RegisterPacket<T>(Action<T> handler)
where T: IPacket
{
_Handlers[typeof (T)] = packet => handler((T) packet);
}
private void ProcessReceivedPacket(IPacket packet)
{
Action<IPacket> handler;
if (!_Handlers.TryGetValue(packet.GetType(), out handler))
{
// Error handling here. No packet handler exists for this type of packet.
return;
}
handler(packet);
}
}
class Program
{
private static PacketService _PacketService = new PacketService();
static void Main(string[] args)
{
PacketService.RegisterPacket<FooPacket>(HandleFooPacket);
}
public static void HandleFooPacket(FooPacket packet)
{
// Do something with the packet
}
}
您创建的每种类型的包都注册一个特定于该类型包的处理程序。使用ConcurrentDictionary使锁定变得多余。