1. 程式人生 > >設計模式系列(十三)迭代器模式(Iterator Pattern)

設計模式系列(十三)迭代器模式(Iterator Pattern)

// 迭代器模式
// IteratorPattern.h檔案

#ifndef ITERATOR
#define ITERATOR

#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <list>

using std::string;
using std::cout;
using std::cin;
using std::endl;
using std::vector;
using std::list;

// 迭代器模式中的迭代器抽象類
// 模板用來確定迭代器遍歷的集合元素型別
template < class Item >
class Iterator
{
public:
	Iterator(){}
	virtual ~Iterator(){}

    virtual void first () = 0;
    virtual void next  () = 0;
    virtual bool isDone() = 0;
    virtual Item* currentItem() = 0;
};

// 迭代器要遍歷的選單項中的條目:餐廳的一種菜
class MenuItem
{
public:
    MenuItem(string name, string description, bool vegetarian, double price)
    {
        this->name = name;
        this->description = description;
        this->vegetarian = vegetarian;
        this->price = price;
    }

    string getName();
    string getDescription();
    double getPrice();
    bool isVegetarian();
    string toString();
private:
    string name;
    string description;
    bool   vegetarian;
    double price;
};

// 迭代器模式中的迭代器具體類
// 1. vector迭代器
template < class Item >
class VectorIterator : public Iterator < Item >
{
public:
    VectorIterator(vector < Item > items)
    {
        this->items = items;
        this->position = 0;
    }

    void first();
    void next();
    bool isDone();
    Item* currentItem();
private:
    vector < Item > items;
    int position;
};

// 1. vector迭代器
template < class Item >
void VectorIterator < Item > ::first()
{
    position = 0;
}

template < class Item >
void VectorIterator < Item > ::next()
{
    if (position < items.size())
    {
        position++;
    }
}

template < class Item >
bool VectorIterator < Item > ::isDone()
{
    if (position >= items.size())
    {
        return true;
    }
    else
    {
        return false;
    }
}

template < class Item >
Item* VectorIterator < Item > ::currentItem()
{
    if (position < items.size())
    {
        return &(items[position]);
    }
    else
    {
        return NULL;
    }
}

// 2. list迭代器
template < class Item >
class ListIterator : public Iterator < Item >
{
public:
    ListIterator(list < Item > items)
    {
        this->items = items;
        this->position = 0;
    }

    void first();
    void next();
    bool isDone();
    Item* currentItem();
private:
    list < Item > items;
    int position;
};

// 2. list迭代器
template < class Item >
void ListIterator < Item > ::first()
{
    position = 0;
}

template < class Item >
void ListIterator < Item > ::next()
{
    if (position < items.size())
    {
        items.erase(items.begin());
    }
}

template < class Item >
bool ListIterator < Item > ::isDone()
{
    if (position >= items.size())
    {
        return true;
    }
    else
    {
        return false;
    }
}

template < class Item >
Item* ListIterator < Item > ::currentItem()
{
    if (position < items.size())
    {
        return &(*(items.begin()));
    }
    else
    {
        return NULL;
    }
}

// 迭代器模式中的抽象集合角色(Aggregate)
template < class Item >
class Menu
{
public:
    Menu(){}
    virtual ~Menu(){}

    // 集合角色中用來建立迭代器角色的函式,留給子類實現
    virtual Iterator < Item > * createIterator() = 0;
};

// 迭代器模式中的具體集合角色(Concrete Aggregate)
template < class Item >
class DinerMenu : public Menu < Item >
{
public:
    DinerMenu() 
    {
        addItem("Vegetarian BLT",
            "(Fakin') Bacon with lettuce & tomato on whole wheat", true, 2.99);
        addItem("BLT",
            "Bacon with lettuce & tomato on whole wheat", false, 2.99);
        addItem("Soup of the day",
            "Soup of the day, with a side of potato salad", false, 3.29);
        addItem("Hotdog",
            "A hot dog, with saurkraut, relish, onions, topped with cheese",
            false, 3.05);
        addItem("Steamed Veggies and Brown Rice",
            "Steamed vegetables over brown rice", true, 3.99);
        addItem("Pasta",
            "Spaghetti with Marinara Sauce, and a slice of sourdough bread",
            true, 3.89);
    }

    void addItem(string name, string description, bool vegetarian, double price);
    vector < Item > getMenuItems();
    Iterator < Item > * createIterator();
private:
    vector < Item > menuItems;
};

// vector
template < class Item >
void DinerMenu < Item > ::addItem(string name, string description, bool vegetarian, double price)
{
    MenuItem mu(name, description, vegetarian, price);
    menuItems.push_back(mu);
}

template < class Item >
vector < Item > DinerMenu < Item > ::getMenuItems()
{
    return menuItems;
}

template < class Item >
Iterator < Item > * DinerMenu < Item > ::createIterator()
{
    return new VectorIterator < Item >(menuItems);
}

template < class Item >
class PancakeHouseMenu : public Menu < Item >
{
public:
    PancakeHouseMenu()
    {
        addItem("K&B's Pancake Breakfast",
            "Pancakes with scrambled eggs, and toast",
            true,
            2.99);

        addItem("Regular Pancake Breakfast",
            "Pancakes with fried eggs, sausage",
            false,
            2.99);

        addItem("Blueberry Pancakes",
            "Pancakes made with fresh blueberries",
            true,
            3.49);

        addItem("Waffles",
            "Waffles, with your choice of blueberries or strawberries",
            true,
            3.59);
    }

    void addItem(string name, string description, bool vegetarian, double price);
    list < Item > getMenuItems();
    Iterator < Item > * createIterator();
private:
    list < Item > menuItems;
};

// list
template < class Item >
void PancakeHouseMenu < Item > ::addItem(string name, string description, bool vegetarian, double price)
{
    MenuItem mu(name, description, vegetarian, price);
    menuItems.push_back(mu);
}

template < class Item >
list < Item > PancakeHouseMenu < Item > ::getMenuItems()
{
    return menuItems;
}

template < class Item >
Iterator < Item > * PancakeHouseMenu < Item > ::createIterator()
{
    return new ListIterator < Item >(menuItems);
}

// 服務員來使用這兩個選單
template < class Item >
class Waitress
{
public:
    Waitress(PancakeHouseMenu < Item > pancakeHouseMenu,
        DinerMenu < Item > dinerMenu)
    {
        this->pancakeHouseMenu = pancakeHouseMenu;
        this->dinerMenu = dinerMenu;
    }

    void printMenu();
private:
    PancakeHouseMenu < Item > pancakeHouseMenu;
    DinerMenu < Item > dinerMenu;

    void printMenu(Iterator < Item > * iterator)
    {
        while (!iterator->isDone()) {
            Item menuItem = *(iterator->currentItem());
            cout << menuItem.getName() << ", " << endl;
            cout << menuItem.getPrice() << " -- " << endl;
            cout << menuItem.getDescription() << endl;

            iterator->next();
        }
    }
};

// 服務員來使用這兩個選單
template < class Item >
void Waitress < Item > ::printMenu()
{
    Iterator < Item > *pancakeIterator = pancakeHouseMenu.createIterator();
    Iterator < Item > *dinerIterator = dinerMenu.createIterator();

    cout << "MENU\n----\nBREAKFAST" << endl;
    printMenu(pancakeIterator);
    cout << "\nLUNCH" << endl;
    printMenu(dinerIterator);
}

#endif

// IteratorPattern.cpp檔案

#include "IteratorPattern.h"

// 迭代器要遍歷的選單項中的條目:餐廳的一種菜
string MenuItem::getName()
{
    return name;
}

string MenuItem::getDescription()
{
    return description;
}

double MenuItem::getPrice()
{
    return price;
}

bool MenuItem::isVegetarian()
{
    return vegetarian;
}

string MenuItem::toString()
{
    char buf[8];
    sprintf_s(buf, "%d", price);
    return (name + ", $" + buf + "\n   " + description);
}

// IteratorPatternTest.cpp檔案

#include "IteratorPattern.h"

void main()
{
    PancakeHouseMenu < MenuItem > pancakeHouseMenu;
    DinerMenu < MenuItem > dinerMenu;

    Waitress<MenuItem> waitress(pancakeHouseMenu, dinerMenu);

    waitress.printMenu();
}

相關推薦

設計模式系列十三模式(Iterator Pattern)

// 迭代器模式 // IteratorPattern.h檔案 #ifndef ITERATOR #define ITERATOR #include <iostream> #include <iomanip> #include <string> #include <

23種設計模式十三模式python_c++實現) .md

23種設計模式之(二十三)迭代器模式(Iterator) 本文主要介紹23種設計模式之迭代器模式,附詳細python/c++示例程式碼。 概念 應用場景 注意事項 程式碼示例 總結 程式碼連結 迭代器模式(Iterator) 概念 迭代模式,是行為模式之一

常用軟體設計模式模式

迭代器模式不常用,很多高階語言都將該模式封裝在語言中了,入C#的 foreach in 但是有必要了解一下 迭代器模式:提供一個方法順序訪問一個聚合物件中各個元素,而又不暴露該物件的內部表示。 優點: 1、它支援以不同的方式遍歷一個聚合物件。     &nb

設計模式—— 模式

一、含義 提供一種方法順序訪問一個聚合物件中的各個元素,而又不暴露其內部的表示。當我們在專案中需要遍歷不同的集合、陣列時,可以考慮使用迭代器模式,提供一個統一的遍歷方法。 二、要點 1.迭代器將遍歷聚合的工作封裝進一個物件中。 2.迭代器提供一個通用的介面,讓我們遍歷聚合的項,當我們

java/android 設計模式學習筆記20---模式

  我們這篇部落格來介紹一下迭代器模式(Iterator Pattern),又稱為遊標(Cursor Pattern)模式,是行為型設計模式之一。迭代器模式算是一個比較古老的設計模式,其源於對容器的訪問,比如 Java 中的 List、Map、陣列等,我們知道對

Java程式設計師從笨鳥到菜鳥之四十五大話設計模式模式和命令模式

歡迎關注微信賬號:java那些事:csh624366188.每天一篇java相關的文章 java交流工作群1: 77800592(已滿) java交流學生群2:234897635(已滿) java交流工作群3:94507287 java交流工作群4: 272265434 我的郵箱:

設計模式10 模式--行為型

定義 迭代器模式(Iterator Pattern):提供一種方法來訪問聚合物件,而不用暴露這個物件的內部表示。 角色 抽象迭代器(Iterator) 抽象迭代器定義了訪問和遍歷元素的介面,一般宣告如下方法:用於獲取第一個元素的first(),用

C++菜鳥學習筆記系列9——

C++菜鳥學習筆記系列(9) 本期主題:迭代器介紹 我們在C++菜鳥學習筆記系列(7)、C++菜鳥學習筆記系列(8)中分別介紹了C++語言標準庫型別string,vector 的定義及使用。 對於string型別的物件我們可以通過範圍for語句和索引的方式訪問其

設計模式十七模式

迭代器模式(Iterator)提供一種方法順序訪問一個聚合物件中的各個元素,而又不暴露改物件的內部表示,類圖來源 https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=971311629,3818362496&fm=26&

我所理解的設計模式C++實現——模式Iterator Pattern

概述:         在現在的電視機中,我們使用[後一個]和[前一個]按鈕可以很方便的換臺,當按下[後一個]按鈕時,將切換到下一個預置的頻道。想象一下在陌生的城市中的旅店中看電視。當改變頻道時,重要的不是幾頻道,而是節目內容。如果對一個頻道的節目不感興趣,那麼可以換下一個頻道,而不需要知道它是幾頻道。  

設計模式十九模式行為型

一、簡介(Brief Introduction)        提供一種方法順序訪問一個聚合物件中各個元素,而又不需暴露該物件的內部表示 例子1:電視遙控器的頻道遍歷   二、模式分析(Analysi

設計模式Java隨筆模式

迭代器模式(Iterator Pattern):最常被使用的幾個模式之一,被廣泛的應用到Java API中,如Java集合(Collection)框架中,就有用迭代器來遍歷集合中的元素(在Java開發中,儘量不要自己寫迭代器模,使用Java API提供的Iterator一般就

軟體設計模式學習二十模式

> 迭代器模式是一種使用頻率非常高的設計模式,迭代器用於對一個聚合物件進行遍歷。通過引入迭代器可以將資料的遍歷功能從聚合物件中分離出來,聚合物件只負責儲存資料,聚合物件只負責儲存資料,而遍歷資料由迭代器來完成。 ## 模式動機 一個聚合物件,如一個列表(List)或者一個集合(Set),應該提供一

設計模式十七——模式ArrayList 集合應用原始碼分析

1 看一個具體的需求 編寫程式展示一個學校院系結構:需求是這樣,要在一個頁面中展示出學校的院系組成,一個學校有多個學院, 一個學院有多個系。如圖: 2 傳統的設計方案(類圖) 3 傳統的方式的問題分析 1) 將學院看做是學校的子類,系是學院的子類,這樣實

js設計模式---叠模式

內部表 spa 需要 興趣 編程 log function cnblogs style 定義:   叠代器模式是指提供一種方法,順序訪問一個聚合對象中的各個元素,而又不需要暴露該對象的內部表示,叠代器模式可以把叠代的過程從業務邏輯中分離出來,使用叠代器模式,即使不關心對象的

面向對象的設計模式十三,解釋模式

bst doc BE private integer 回來 import new 得到 解釋器模式,從字面上解釋來說就是為一個文法(具有特定語法的形式的語句或表達式)

PHP設計模式系列:工廠方法模式

工廠方法模式 工廠方法模式(Factory Method Pattern)又稱為工廠模式,也叫虛擬構造器(Virtual Constructor)模式或者多型工廠(Polymorphic Factory)模式,它屬於類建立型模式。在工廠方法模式中,工廠父類負責

C++菜鳥學習筆記系列15——語句

C++菜鳥學習筆記系列(15) 本期主題:迭代語句(包括while語句、傳統for語句、範圍for語句、do…while語句) 迭代語句就是我們常說的迴圈,它重複執行一些操作直到滿足某個條件才停下來。不同的是while語句和for語句都是在執行迴圈體之前先進行條

設計模式10模式

ali 它的 alt set override getname () mov 價格 叠代器模式提供了一種方法順序訪問一個聚合對象中的各個元素,而又不暴露其內部的表示。 下面我們利用java自帶的叠代器接口實現這個叠代器模式 首先我們定義一個自定義的集合類,並實現它的

Python3.5十三&生成器

什麽 結束 環比 第一個元素 amp 訪問 事先 這也 一個 叠代器是訪問集合元素的一種方式。叠代器對象從集合的第一個元素開始訪問,直到所有的元素被訪問完結束。叠代器只能往前不會後退,不過這也沒什麽,因為人們很少在叠代途中往後退。另外,叠代器的一大優點是不要求事先準備好整個