实现迭代器模式示例,添加任务结构体、迭代器接口及具体实现,增强代码可读性
This commit is contained in:
@@ -0,0 +1,92 @@
|
||||
/*
|
||||
实例:
|
||||
汤宝宝有一张TODO表,记录着自己想干的事情。
|
||||
*/
|
||||
|
||||
// 任务结构体 - 迭代器元素
|
||||
interface Todo {
|
||||
content: string;
|
||||
done: boolean;
|
||||
}
|
||||
|
||||
// 迭代器接口
|
||||
interface IIterator {
|
||||
First(): Todo;
|
||||
Next(): Todo;
|
||||
isDone(): boolean;
|
||||
CurrentItem(): number;
|
||||
}
|
||||
|
||||
// 具体迭代器 - 汤宝宝的TODO表迭代器
|
||||
|
||||
class TodoListIterator implements IIterator {
|
||||
todoList: TodoList;
|
||||
current: number;
|
||||
constructor(todoList: TodoList) {
|
||||
this.todoList = todoList;
|
||||
this.current = 0;
|
||||
}
|
||||
First(): Todo {
|
||||
this.current = 0;
|
||||
return this.todoList.todos[this.current];
|
||||
}
|
||||
Next(): Todo {
|
||||
this.current += 1;
|
||||
return this.todoList.todos[this.current];
|
||||
}
|
||||
isDone(): boolean {
|
||||
return this.current >= this.todoList.todos.length;
|
||||
}
|
||||
CurrentItem(): number {
|
||||
if (this.current < 0 || this.current >= this.todoList.todos.length) {
|
||||
return this.todoList.todos.length;
|
||||
}
|
||||
return this.current + 1;
|
||||
}
|
||||
}
|
||||
|
||||
// 集合接口
|
||||
interface ICollection {
|
||||
createIterator(): IIterator;
|
||||
}
|
||||
|
||||
// 具体集合 - 汤宝宝的TODO表
|
||||
class TodoList implements ICollection {
|
||||
todos: Todo[];
|
||||
constructor(todos: Todo[]) {
|
||||
this.todos = todos;
|
||||
}
|
||||
|
||||
createIterator(): IIterator {
|
||||
return new TodoListIterator(this);
|
||||
}
|
||||
}
|
||||
|
||||
(function () {
|
||||
console.log("============= 迭代器模式 =============");
|
||||
|
||||
// 创建TODO表并添加任务
|
||||
const todoList = new TodoList([
|
||||
{ content: "学习Go语言", done: true },
|
||||
{ content: "完成设计模式作业", done: false },
|
||||
{ content: "锻炼身体", done: false },
|
||||
]);
|
||||
|
||||
// 创建迭代器
|
||||
const iterator = todoList.createIterator();
|
||||
|
||||
// 使用迭代器遍历TODO表
|
||||
for (
|
||||
let item = iterator.First();
|
||||
!iterator.isDone();
|
||||
item = iterator.Next()
|
||||
) {
|
||||
console.log(
|
||||
`当前第 ${iterator.CurrentItem()} 项任务内容: ${
|
||||
item ? item.content : ""
|
||||
} 是否完成: ${item && item.done ? "已完成" : "未完成"}`
|
||||
);
|
||||
}
|
||||
|
||||
console.log("\n=========== 迭代器模式结束 ===========");
|
||||
})();
|
||||
Reference in New Issue
Block a user