本文共 1148 字,大约阅读时间需要 3 分钟。
书里面都是Java实现的,书上的知识点不再赘余。这里用c++把书上的设计模式实现一下,加深自己对于该设计模式的理解。
定义:
特点:
通过迭代器隔离算法和容器。
为遍历不同的集合结构提供一个统一的接口,从而支持同样的算法在不同的集合结构上进行操作。
缺点:
虚函数调用是有性能成本的。需要根据虚函数的表指针去找你的函数地址,每次都要进行二次指针的间接运算。
模板是编译时多态,虚函数是运行时多态。运行是多态的性能差于编译是多态,因为编译时把工作做了,运行时就不需要去调用函数的地址了。所以,基于模板方式的泛型编程迭代器,性能要高于基于虚函数的迭代器。
但是这种基于虚函数的迭代器的设计模式在其他语言里是常见的,比如Java、C#、PHP,即依然是基于运行时多态来实现iterator模式,因为其他的语言不支持编译时多态。因此,当今的iterator模式,c++很少用如下的方式去实现,但是其他语言是这样实现的。
templateclass Iterator{public: virtual void first() = 0; virtual void next() = 0; virtual bool isDone() const = 0; virtual T& current() = 0;};template class MyCollection{ public: Iterator GetIterator(){ //返回一个迭代器 } };template class CollectionIterator : public Iterator { MyCollection mc;public: CollectionIterator(const MyCollection & c): mc(c){ } void first() override { } void next() override { } bool isDone() const override{ } T& current() override{ }};//使用范例void MyAlgorithm(){ MyCollection mc; Iterator iter= mc.GetIterator(); for (iter.first(); !iter.isDone(); iter.next()){ cout << iter.current() << endl; } }
转载地址:http://zapxl.baihongyu.com/