栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

【设计模式】迭代器模式

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【设计模式】迭代器模式

概念

行为模式


类图


代码
#include 
#include 

using namespace std;

class Profile {
public:
    Profile (int index, string email) {
        id = index;
        content = email;
    }

    void GetId() {
        cout << "Id get! " << id << endl;
    }

    void GetEmail() {
        cout << "Email get! " << content << endl;
    }

private:
    int id;
    string content;
};

class ProfileIterator {
public:
    virtual ~ProfileIterator() = default;
    virtual Profile* GetNext() = 0;
    virtual bool HasMore() = 0;
};

class SocialNetwork {
public:
    virtual ProfileIterator* CreateFriendsIterator(int profileId) = 0;
    virtual ProfileIterator* CreateCoworkersIterator(int profileId) = 0;
};


class WeChat;
class WeChatIterator : public ProfileIterator {
public:
    WeChatIterator(WeChat* weChat, int profileId, const string& type) {
        this->weChat = weChat;
        this->profileId = profileId;
        this->type = type;
    };

    Profile* GetNext() override {
        if (HasMore()) {
            currentPosition++;
            return profiles[currentPosition - 1];
        }

        return nullptr;
    }

    bool HasMore() override {
        LazyInit();
        return currentPosition < profiles.size();
    }

private:
    WeChat* weChat;
    int profileId;
    string type;
    int currentPosition{0};
    vector profiles;

    void LazyInit() {
        if (profiles.empty()) {
            cout << "WeChatIterator lazy init." << endl;
            profiles.emplace_back(new Profile(profileId, type));
        }
    }
};

class WeChat : public SocialNetwork {
public:
    ProfileIterator* CreateFriendsIterator(int profileId) override {
        return new WeChatIterator(this, profileId, "friends");
    }

    ProfileIterator* CreateCoworkersIterator(int profileId) override {
        return new WeChatIterator(this, profileId, "coworkers");
    }
};

class SocialSpammer {
public:
    static void Send(ProfileIterator* iterator, const string& message) {
        while (iterator->HasMore()) {
            auto profile = iterator->GetNext();
            profile->GetId();
            profile->GetEmail();
        }
    }
};

int main(int argc, char *argv[]) {
    auto network = new WeChat();
    auto coworkerIter = network->CreateCoworkersIterator(0);
    auto friendIter = network->CreateFriendsIterator(1);

    SocialSpammer::Send(coworkerIter, "VIP MSG!");
    SocialSpammer::Send(friendIter, "JUNK MSG!");

    delete network;
    delete coworkerIter;
    delete friendIter;

    return 0;
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1001133.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号