gameClient/assets/scripts/network/messageDispatcher.ts

72 lines
1.8 KiB
TypeScript
Raw Normal View History

// 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)) // 顺序执行
}
}
}