一、行为型模式常考题
常见行为型设计模式
1.迭代器模式(Iterator
):通过统一的接口迭代对象
2.观察者模式(Observer
):对象发生改变的时候,观察者执行相应动作
3.策略模式(Strategy
):针对不同规模输入使用不同的策略
二、迭代器模式
迭代器模式(Iterator
)
1.Python
内置对迭代器模式的支持
2.比如我们可以用for
遍历各种 Iterable
的数据类型
3.Python
里可以实现__next__
和__iter__
实现迭代器
from collections import deque
class Stack: # 使用组合的例子
def __init__(self):
self._deque = deque() # has a deque()
def push(self, val):
return self._deque.append(val)
def pop(self):
return self._deque.pop()
def empty(self):
return len(self._deque) == 0
def __iter__(self):
res = [i for i in self._deque]
for i in reversed(res):
yield i
s = S