建站行业有前途,自助建站公司,网站建设心得,专业网站建设公司哪家专业1、模式标准
模式名称#xff1a;迭代器模式
模式分类#xff1a;行为型
模式意图#xff1a;提供一种方法顺序访问一个聚合对象中的各个元素#xff0c;且不需要暴露该对象的内部表示.
结构图#xff1a;
适用于#xff1a; 1、当你需要遍历一个复杂的数据结构…1、模式标准
模式名称迭代器模式
模式分类行为型
模式意图提供一种方法顺序访问一个聚合对象中的各个元素且不需要暴露该对象的内部表示.
结构图
适用于 1、当你需要遍历一个复杂的数据结构如树或图而不想公开其内部表示时。 2、当你有一个集合对象需要提供多种遍历方式或者需要自定义遍历方式时。 3、当你需要让代码独立于特定的类或接口使代码能够与多种数据类型一起工作时。 主要成员 迭代器接口Iterator定义遍历元素所需的方法例如 next()hasNext() 等。 具体迭代器Concrete Iterator实现迭代器接口并跟踪遍历的当前位置。 聚合接口Aggregate定义创建相应迭代器对象的接口。 具体聚合Concrete Aggregate实现聚合接口返回具体迭代器的实例。 2、分析与设计
在游戏中会经常用到迭代器一般情况下我们定义一个index随着游戏或者操作进行index来进行下一步对象或者操作。这里我们用到的场景是新手指引当某个事件发生时新手指引聚合器创建一个指引迭代器指引迭代器指引玩家一步一步的按顺序完成。
意图提供一种方法顺序访问一个聚合对象(新手指引聚合器)中的各个元素(新手指引)且不需要暴露该对象的内部表示
3、开始打造 // 聚合接口
export interface IAggregate {createIterator(): IIterator
}
// 具体的新手指引聚合
export class GuideAggregate implements IAggregate {steps: GuideStep[] []addStep(step: GuideStep) {this.steps.push(step)}createIterator() {return new GuideIterator(this.steps)}
}
// 迭代器接口
export interface IIterator {hasNext(): booleannext(): any
} // 具体的新手指引迭代器
export class GuideIterator implements IIterator {private index: number 0steps: GuideStep[] []constructor(steps: GuideStep[]) {this.steps steps}hasNext(): boolean {return this.index this.steps.length;}next(): GuideStep | null {if (this.hasNext()) {return this.steps[this.index];} else {return null;}}
} // 指引步骤
export class GuideStep {private onClickResolver: (() void) | null null;guideItem: IGuideItemconstructor(_item: IGuideItem) {this.guideItem _item}execute() {const targetNode find(this.guideItem.targetNodePath)// 注册事件监听器targetNode.on(Node.EventType.TOUCH_START, this.handleClick)return targetNode // 外面要用到先返回}// 当用户点击时解决 Promiseprivate handleClick () {const targetNode find(this.guideItem.targetNodePath)targetNode.off(Node.EventType.TOUCH_START, this.handleClick)if (this.onClickResolver) {this.onClickResolver();}}// 返回一个 Promise该 Promise 在用户点击后被resolveonClick(): Promisevoid {console.log(等待点击)return new Promise((resolve) {this.onClickResolver resolve;});}
}
4、开始使用 let guides: IGuideItem[] [{group: battle_start,targetNodePath: root/UICanvas/battle_index/help_move_up,text: 点击的虚框,text_size: [200, 200],text_pos_index: 3}, {group: battle_start,targetNodePath: root/UICanvas/battle_index/help_move_up,text: 点击的虚框,text_size: [200, 200],text_pos_index: 3}]// 开始本次的新手指引let guideAggregate new GuideAggregate();guides.forEach((_item) {guideAggregate.addStep(new GuideStep(_item));})async function runGuide(guide: GuideAggregate) {// 创建新手指引的指引层PlayerGuideSystem.createGuideNodes(comp)let iterator guide.createIterator();while (iterator.hasNext()) {console.log(准备指引)let step iterator.next();if (step ! null) {step.execute();await step.onClick(); // 等待用户点击console.log(点击完成)}}// 清理新手指引的指引层PlayerGuideSystem.clearNodes()console.log(指导层清理完成)}runGuide(guideAggregate);
完工