Design Pattern Examples
Overview of object-oriented design patterns
iterator_class.py
Go to the documentation of this file.
12
13from abc import ABC, abstractmethod
14from typing import Any
15
16
18
19
25 def __init__(self, key = "", value = "") -> None:
26 self.Key = key
27 self.Value = value
28
29
33
34
35
37
38
39
56class IIterator(ABC):
57
58
59 @abstractmethod
60 def Reset(self) -> None:
61 pass
62
63
68 def Next(self) -> Any:
69 pass
70
71
72
74
75
76
95class Iterator(IIterator):
96
97
103 def __init__(self, items : list, numItems: int) -> None:
104 self._items = items.copy()
105 self._numItems = numItems
106 self._index = 0
107
108
114
115
120 def Next(self) -> Any:
121 retrieved_item = None
122 if self._index < self._numItems:
123 retrieved_item = self._items[self._index]
124 self._index += 1
125 return retrieved_item
126
127
128 def Reset(self) -> None:
129 self._index = 0
130
131
132
134
135
136
145 # Hardcoded data to be iterated over.
146 # The number of keys must match the number of values.
147
148
149 _keys = [ "One", "Two", "Three" ]
150
151
152 _values = [ "Value 1", "Value 2", "Value 3" ]
153
154
162 def GetItems(self) -> IIterator:
163 items = [] # type:list[ItemPair]
164
165 numItems = len(IteratorContainer_Class._keys)
166 for index in range(0, numItems):
167 items.append(ItemPair(IteratorContainer_Class._keys[index],
168 IteratorContainer_Class._values[index]))
169
170 return Iterator(items, len(items))
171
172
173
180 def GetKeys(self) -> IIterator:
181 return Iterator(IteratorContainer_Class._keys, len(IteratorContainer_Class._keys))
182
183
184
191 def GetValues(self) -> IIterator:
192 return Iterator(IteratorContainer_Class._values, len(IteratorContainer_Class._values))
None Reset(self)
Start iteration from beginning of container.
Any Next(self)
Retrieve the next item from the container.
Represents a key/value pair where the key and value are strings.
None __init__(self, key="", value="")
Constructor.
Represents a container that offers up two kinds of iterators for the hardcoded contents,...
IIterator GetItems(self)
Retrieve an iterator over the data that returns an ItemPair object containing both key and value for ...
IIterator GetValues(self)
Retrieve an iterator over the "value" part of the data, where the data returned from the iterator is ...
IIterator GetKeys(self)
Retrieve an iterator over the "key" part of the data, where the data returned from the iterator is a ...
Represents an iterator for a container by implementing the IIterator interface.
None Reset(self)
Reset the iterator to the beginning.
None __init__(self, list items, int numItems)
Constructor.
Any Next(self)
Fetches the next item in the iteration, if any.
_numItems
The number of items in the array of items.
_index
The index into the _items array to the next item.