gameClient/assets/scripts/network/messageDispatcher.ts

72 lines
1.8 KiB
TypeScript
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// MessageDispatcher.ts
/** 消息处理器类型 */
export type MessageHandler = (data: any) => void
export class MessageDispatcher {
private static _instance: MessageDispatcher
private _handlers: Map<number, MessageHandler[]> = new Map()
/** 单例模式 */
public static get Instance(): MessageDispatcher {
if (!this._instance) {
this._instance = new MessageDispatcher()
}
return this._instance
}
/**
* 注册消息处理器(允许多个 Handler
* @param msgId 消息ID
* @param handler 回调函数
*/
public On(msgId: number, handler: MessageHandler): void {
if (!this._handlers.has(msgId)) {
this._handlers.set(msgId, [])
}
this._handlers.get(msgId)?.push(handler) // 添加到队列
}
/**
* 移除指定的消息处理器(通过函数引用精准匹配)
* @param msgId 消息ID
* @param handler 要移除的回调函数
*/
public Off(msgId: number, handler: MessageHandler): void {
const handlers = this._handlers.get(msgId)
if (!handlers) return
// 过滤掉指定的 handler
const newHandlers = handlers.filter((h) => h !== handler)
this._handlers.set(msgId, newHandlers)
}
/**
* 消息派发器中handler数量
* @param msgId 消息ID
* @returns 返回消息派发器中handler数量
*/
public Size(msgId: number): number {
if (msgId === 0) {
return this._handlers.size
}
const handlers = this._handlers.get(msgId)
if (handlers) {
return handlers.length
}
return 0
}
/**
* 派发消息(按注册顺序执行所有 Handler
* @param msgId 消息ID
* @param msg 消息数据
*/
public Dispatch(msgId: number, msg: any): void {
const handlers = this._handlers.get(msgId)
if (handlers) {
handlers.forEach((handler) => handler(msg)) // 顺序执行
}
}
}