设计模式——迭代器模式

csdn推荐

迭代器模式(Iterator)

迭代器模式是一种行为设计模式, 让你能在不暴露集合底层表现形式 (列表、 栈和树等) 的情况下遍历集合中所有的元素。

提供一种方法顺序访问一个聚合对象中的各个元素,而又不暴露该对象中的内部表示

当我们要访问一个聚合对象,而且不管这些对象是什么都需要遍历的时候,应该考虑使用迭代器模式,另外当需要对聚集对象有多种方式遍历时,也可以考虑迭代器模式。

迭代器模式为遍历不同的聚集结构提供了诸如开始、下一个、是否结束、当前哪一项等统一的接口

现在高级语言已经将这个模式用在语言本身,学习价值大于使用价值。

#include 
#include 
#include 
using namespace std;
// C++ 有自己的迭代器实现,可以与标准库定义的不同泛型容器一起使用。
template 
class Iterator{
public:
    typedef typename std::vector::iterator iter_type;
    Iterator(U *p_data, bool reverse = false):m_p_data_(p_data){
        m_it_ = m_p_data_->m_data_.begin();
    }
    void First(){
        m_it_ = m_p_data_->m_data_.begin();
    }
    void Next(){
        m_it_++;
    }
    bool IsDone(){
        return (m_it_ == m_p_data_->m_data_.end());
    }
    iter_type Current(){
        return m_it_;
    }
private : 
    U *m_p_data_;
    iter_type m_it_;
};
// 通用集合/容器提供了一种或多种方法来检索与集合类兼容的新迭代器实例。
template 
class Container{
    friend class Iterator;
public:
    void Add(T a){
        m_data_.push_back(a);
    }
    Iterator *CreateIterator(){
        return new Iterator(this);
    }
private:
    vector m_data_;
};
// 自定义类
class Data{
public:
    Data(int a=0):m_data_(a){}
    void set_data(int a){
        m_data_ = a;
    }
    int data(){
        return m_data_;
    }
private:
    int m_data_;
};
// 客户端代码可能知道也可能不知道具体迭代器或集合类,对于此实现,容器是通用的,因此可以与 int 或自定义类一起使用。
void Client(){
    cout << "________________Iterator with int______________________________________" << endl;
    Container cont;
    for (int i = 0; i<10; i++){
        cont.Add(i);
    }
    Iterator<int, Container> *it = cont.CreateIterator();
    for (it->First(); !it->IsDone(); it->Next()){
        cout <Current() << endl;
    }
    Container cont2;
    Data a(100), b(200), c(300);
    cont2.Add(a);
    cont2.Add(b);
    cont2.Add(c);
    cout << "________________Iterator with custom Class______________________________" << endl;
    Iterator<Data, Container> *it2 = cont2.CreateIterator();
    for (it2->First(); !it2->IsDone(); it2->Next()){
        cout <Current()->data() << endl;
    }
    delete it;
    delete it2;
}
int main(){
    Client();
    return 0;
}

输出:

________________Iterator with int______________________________________
0
1
2
3
4
5
6
7
8
9
________________Iterator with custom Class______________________________
100
200
300

文章来源:https://blog.csdn.net/weixin_42903300/article/details/139772847



微信扫描下方的二维码阅读本文

© 版权声明
THE END
喜欢就支持一下吧
点赞5 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容