您好,欢迎来到尚车旅游网。
搜索
您的当前位置:首页详解CocosCreator消息分发机制

详解CocosCreator消息分发机制

来源:尚车旅游网
详解CocosCreator消息分发机制

概述

本篇开始介绍游戏业务架构相关的内容。在游戏业务层,所有需要隔离的系统和模块间通信都可以通过消息分发解耦。例如⽹络返回通知、数据更新同步到界⾯等。

消息分发基于观察者模式设计。需要处理消息的地⽅向消息中⼼注册监听回调,派发消息时,调⽤消息中⼼的派发接⼝遍历该消息的监听队列,调⽤对应的回调⽅法。

具体⽅案

先定义监听回调类型

/**

* 消息监听回调⽅法 */

export type NotifyListener = (src: any, data: any) => void;

通过key-value⽅式保存监听队列

private static msg2listDict: Dictionary< string, Array > = new Dictionary< string, Array >();

接⼝定义

/**

* 添加多次监听者,需要⼿动移除 * @param msg * @param listener * @param target */

public static addListener(msg: string, listener: NotifyListener, target?: any): void {} /**

* 添加单次监听者,事件触发后即移除 * @param msg * @param listener * @param target */

public static addOnceListener(msg: string, listener: NotifyListener, target?: any): void {} /**

* 移除指定消息指定的监听者 * @param msg * @param listener */

public static removeMsgListener(msg: string, listener: NotifyListener): void {} /**

* 移除指定消息所有监听者 * @param msg */

public static removeMsgAllListeners(msg: string): void {} /**

* 移除指定⽬标对指定消息的监听 * @param msg * @param target */

public static removeTargetMsgListen(msg: string, target: any): void {} /**

* 移除指定⽬标所有消息监听 * @param target */

public static removeTargetAllMsgListen(target: any): void {} /**

* 派发消息

* @param msg * @param src

* @param data */

public static notify(msg: string, src: any, data: any): void {}

在添加移除实现中,需要注意某消息可能正在派发。

对于⼀个消息新添加的监听者,应该在当前队列消息派发完后再派发,因此,添加⼀个待添加队列

private static listener2add: Array = [];

在添加监听者时做以下判断

// 该消息正在派发,放⼊待添加队列

if (NotifyCenter.notifyMsgs.indexOf(msg) >= 0) { NotifyCenter.listener2add.push(info); return;}

同样在移除监听者时,可能正在派发消息,避免对队列的修改导致for循环异常,添加⼀个待移除队列,派发消息时,如果该监听者在移除队列则不派发。在消息派发完后再将其移出队列

private static listener2remove: Array = [];

在移除监听者时做以下判断

// 该消息正在派发,放⼊待移除队列

if (NotifyCenter.notifyMsgs.indexOf(msg) >= 0) { NotifyCenter.listener2remove.push(list[i]);} else {

list.splice(i, 1);}

派发消息时遍历指定消息下的队列

// 队列不存在,不需要处理

let list = NotifyCenter.msg2listDict.get(msg);if (!list) { return;}

// 标记消息正在派发,多个消息可能同时在派发,同⼀消息可能标记多次NotifyCenter.notifyMsgs.push(msg);

// 处理消息派发

for (let i = 0, n = list.length; i < n; i++) {

NotifyCenter._dispatch(list[i], src, data, false);}

派发消息时先判断是否在移除队列

// 在移除队列,不派发

if (NotifyCenter.listener2remove.indexOf(info) >= 0) { return;}

当前队列派发完后检查待添加队列

// 处理待添加队列派发

for (let i = 0, n = msg2add.length; i < n; i++) { if (listener2add[i].msg == msg) {

NotifyCenter._dispatch(listener2add[i], src, data, true); }}

引⼊消息分发中⼼,隔离的系统、模块间通过消息监听和派发通信,避免互相引⽤耦合。

以上就是详解CocosCreator消息分发机制的详细内容,更多关于CocosCreator消息分发的资料请关注其它相关⽂章!

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- sceh.cn 版权所有 湘ICP备2023017654号-4

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务