diff --git a/16_iterator.cpp b/16_iterator.cpp new file mode 100644 index 0000000..22ccec5 --- /dev/null +++ b/16_iterator.cpp @@ -0,0 +1,58 @@ +#include +#include +#include + +using namespace std; + +class Iterator { +public: + virtual bool has_next() = 0; + virtual int next() = 0; + virtual ~Iterator() = default; +}; + +class IntContainer { +private: + vector v; +public: + void add_i(int i) { + v.push_back(i); + } + + shared_ptr begin(); +}; + +class IntIterator : public Iterator { + vector& v; + int index; +public: + IntIterator(vector& v) : v(v), index(0) {} + virtual bool has_next() { + return index != v.size(); + } + + virtual int next() { + index += 1; + return v[index - 1]; + } +}; + +shared_ptr IntContainer::begin() { + return make_shared(this->v); +} + +int main() { + IntContainer c; + c.add_i(1); + c.add_i(3); + c.add_i(5); + c.add_i(6); + + // When you want to design a new container, you just + // implement a iterator, so user don't have to care the + // detail how the container work. + auto v = c.begin(); + while (v->has_next()) { + cout << v->next() << endl; + } +} diff --git a/notes.md b/notes.md index b6b8799..c81d07b 100644 --- a/notes.md +++ b/notes.md @@ -105,3 +105,11 @@ 命令模式通过引入统一的“命令对象”,将请求的发送者(前端)与执行者(后端)解耦。前端只需构造命令并发送,不关心命令的执行细节;而后端根据命令对象来执行相应逻辑。 更重要的是,所有操作都被抽象为统一的命令接口,这使得命令可以统一记录、排队、撤销、重做。多个前端只需绑定相同的命令对象,即可复用相同的后端逻辑,增强了代码复用性与系统扩展性。 + +## 迭代器模式(Iterator) + +集合是一种常用的数据结构,用于维护一组对象。一个集合显然需要一种方式遍历其中的元素。如果针对每一种集合设计一种遍历的方式或者函数,使用者的代码与集合强相关,且使用者可能需要了解集合的实现细节,这显然很麻烦。 + +将集合的遍历行为抽象为通用的迭代器对象可以解决这些问题。集合的设计者只需要提供用于遍历操作的配套对象,使用者通过统一的接口得到下一个元素,直至结束,从而解耦了集合的实现与使用者的遍历逻辑。 + +在 C++ 中,标准库大量使用了这类思想,比如 vector,map 等集合,以及 sort 等算法库。