-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathiterator.go
65 lines (55 loc) · 1.42 KB
/
iterator.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package iterator
// Iterator 迭代器接口
type Iterator interface {
Next() Member // 迭代下一个成员
HasMore() bool // 是否还有
}
// Iterable 可迭代集合接口,实现此接口返回迭代器
type Iterable interface {
CreateIterator() Iterator
}
// Class 班级,包括老师和同学
type Class struct {
name string
teacher *Teacher
students []*Student
}
// memberIterator 班级成员迭代器实现
type memberIterator struct {
class *Class // 需迭代的班级
index int // 迭代索引
}
func (m *memberIterator) Next() Member {
// 迭代索引为-1时,返回老师成员,否则遍历学生slice
if m.index == -1 {
m.index++
return m.class.teacher
}
student := m.class.students[m.index]
m.index++
return student
}
func (m *memberIterator) HasMore() bool {
return m.index < len(m.class.students)
}
// NewClass 根据班主任老师名称,授课创建班级
func NewClass(name, teacherName, teacherSubject string) *Class {
return &Class{
name: name,
teacher: NewTeacher(teacherName, teacherSubject),
}
}
// CreateIterator 创建班级迭代器
func (c *Class) CreateIterator() Iterator {
return &memberIterator{
class: c,
index: -1, // 迭代索引初始化为-1,从老师开始迭代
}
}
func (c *Class) Name() string {
return c.name
}
// AddStudent 班级添加同学
func (c *Class) AddStudent(students ...*Student) {
c.students = append(c.students, students...)
}