另一种迭代器模式和中介者模式 14/30 | Python 主题月
写在前面
本文正在参加「Python主题月」,详情查看活动链接
这个月是 Python 活动月,我决定尝试用 Python 来刷这 30 天的每日一题和随机一题。然后如果周末有精力,我想捣鼓捣鼓这个python-patterns
设计模式对我来说更多的是学习而不是我的个人经验总结,所以我很可能理解偏,如果有大佬见到了请及时指出,我之所以选择在掘金来写一些个人的东西是因为这里的文章质量更高,我不希望后来者看到了这些文章被误导。
另一种迭代器模式
class NumberWords:
"""Counts by word numbers, up to a maximum of five"""
_WORD_MAP = (
"one",
"two",
"three",
"four",
"five",
)
def __init__(self, start, stop):
self.start = start
self.stop = stop
def __iter__(self): # this makes the class an Iterable
return self
def __next__(self): # this makes the class an Iterator
if self.start > self.stop or self.start > len(self._WORD_MAP):
raise StopIteration
current = self.start
self.start += 1
return self._WORD_MAP[current - 1]
# Test the iterator
def main():
"""
# Counting to two...
>>> for number in NumberWords(start=1, stop=2):
... print(number)
one
two
# Counting to five...
>>> for number in NumberWords(start=1, stop=5):
... print(number)
one
two
three
four
five
"""
if __name__ == "__main__":
import doctest
doctest.testmod()
中介者模式
from __future__ import annotations
class ChatRoom:
"""Mediator class"""
def display_message(self, user: User, message: str) -> None:
print(f"[{user} says]: {message}")
class User:
"""A class whose instances want to interact with each other"""
def __init__(self, name: str) -> None:
self.name = name
self.chat_room = ChatRoom()
def say(self, message: str) -> None:
self.chat_room.display_message(self, message)
def __str__(self) -> str:
return self.name
def main():
"""
>>> molly = User('Molly')
>>> mark = User('Mark')
>>> ethan = User('Ethan')
>>> molly.say("Hi Team! Meeting at 3 PM today.")
[Molly says]: Hi Team! Meeting at 3 PM today.
>>> mark.say("Roger that!")
[Mark says]: Roger that!
>>> ethan.say("Alright.")
[Ethan says]: Alright.
"""
if __name__ == "__main__":
import doctest
doctest.testmod()
小结
参考文献
- 无