feat: Iterator
Implemented a demo for the Iterator.
This commit is contained in:
parent
18694cf41f
commit
075d6cb132
58
16_iterator.cpp
Normal file
58
16_iterator.cpp
Normal file
@ -0,0 +1,58 @@
|
||||
#include <iostream>
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
|
||||
using namespace std;
|
||||
|
||||
class Iterator {
|
||||
public:
|
||||
virtual bool has_next() = 0;
|
||||
virtual int next() = 0;
|
||||
virtual ~Iterator() = default;
|
||||
};
|
||||
|
||||
class IntContainer {
|
||||
private:
|
||||
vector<int> v;
|
||||
public:
|
||||
void add_i(int i) {
|
||||
v.push_back(i);
|
||||
}
|
||||
|
||||
shared_ptr<Iterator> begin();
|
||||
};
|
||||
|
||||
class IntIterator : public Iterator {
|
||||
vector<int>& v;
|
||||
int index;
|
||||
public:
|
||||
IntIterator(vector<int>& v) : v(v), index(0) {}
|
||||
virtual bool has_next() {
|
||||
return index != v.size();
|
||||
}
|
||||
|
||||
virtual int next() {
|
||||
index += 1;
|
||||
return v[index - 1];
|
||||
}
|
||||
};
|
||||
|
||||
shared_ptr<Iterator> IntContainer::begin() {
|
||||
return make_shared<IntIterator>(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;
|
||||
}
|
||||
}
|
||||
8
notes.md
8
notes.md
@ -105,3 +105,11 @@
|
||||
命令模式通过引入统一的“命令对象”,将请求的发送者(前端)与执行者(后端)解耦。前端只需构造命令并发送,不关心命令的执行细节;而后端根据命令对象来执行相应逻辑。
|
||||
|
||||
更重要的是,所有操作都被抽象为统一的命令接口,这使得命令可以统一记录、排队、撤销、重做。多个前端只需绑定相同的命令对象,即可复用相同的后端逻辑,增强了代码复用性与系统扩展性。
|
||||
|
||||
## 迭代器模式(Iterator)
|
||||
|
||||
集合是一种常用的数据结构,用于维护一组对象。一个集合显然需要一种方式遍历其中的元素。如果针对每一种集合设计一种遍历的方式或者函数,使用者的代码与集合强相关,且使用者可能需要了解集合的实现细节,这显然很麻烦。
|
||||
|
||||
将集合的遍历行为抽象为通用的迭代器对象可以解决这些问题。集合的设计者只需要提供用于遍历操作的配套对象,使用者通过统一的接口得到下一个元素,直至结束,从而解耦了集合的实现与使用者的遍历逻辑。
|
||||
|
||||
在 C++ 中,标准库大量使用了这类思想,比如 vector,map 等集合,以及 sort 等算法库。
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user