Files
rougelike-demo/client/assets/scripts/App/Msg/MessagePairBase.ts

76 lines
2.2 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

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.

/**
* 消息对定义基类
* 用于定义成对出现的请求和响应消息
*/
export abstract class MessagePair<TReq, TRes> {
/** 请求消息名称 */
abstract readonly requestName: string;
/** 响应消息名称 */
abstract readonly responseName: string;
/** 请求消息类型检查 */
abstract isValidRequest(msg: any): msg is TReq;
/** 响应消息类型检查 */
abstract isValidResponse(msg: any): msg is TRes;
}
/**
* 消息对注册表
* 用于管理所有的消息对
*/
export class MessagePairRegistry {
private static _instance: MessagePairRegistry;
private _pairs: Map<string, MessagePair<any, any>> = new Map();
static getInstance(): MessagePairRegistry {
if (!this._instance) {
this._instance = new MessagePairRegistry();
}
return this._instance;
}
/**
* 注册消息对
* @param pair 消息对实例
*/
register(pair: MessagePair<any, any>): void {
this._pairs.set(pair.requestName, pair);
console.log(`[MessagePairRegistry] Registered message pair: ${pair.requestName} -> ${pair.responseName}`);
}
/**
* 根据请求消息名获取响应消息名
* @param requestName 请求消息名
* @returns 响应消息名如果未找到返回null
*/
getResponseName(requestName: string): string | null {
const pair = this._pairs.get(requestName);
return pair ? pair.responseName : null;
}
/**
* 根据请求消息名获取消息对
* @param requestName 请求消息名
* @returns 消息对实例如果未找到返回null
*/
getPair(requestName: string): MessagePair<any, any> | null {
return this._pairs.get(requestName) || null;
}
/**
* 检查是否为已注册的请求消息
* @param msgName 消息名
*/
isRegisteredRequest(msgName: string): boolean {
return this._pairs.has(msgName);
}
/**
* 获取所有已注册的消息对
*/
getAllPairs(): MessagePair<any, any>[] {
return Array.from(this._pairs.values());
}
}