Design Mode C ++ implementation-iterator Mode

Source: Internet
Author: User

Pattern Defines the iterator Pattern provides a method to access each element in an aggregate object sequentially without exposing its internal representation.

The iterator mode allows us to walk through every element in the aggregation without exposing its internal representation. Place the walk task on the iterator instead of aggregation. This simplifies the aggregation interface and implementation, and also enables different responsibilities.

Mode structure:

<喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + kernel/LT6xve907/kernel + DTprXEtfy0 + kernel/M5b7bus/Ktc/WtLS9qM/g06a1/kernel + vtnA/kernel + kernel/ vDx7XEtqjS5cjnz8LL + cq + KaOsy/keys = "left">

// Menu item class MenuItem {public: MenuItem () {} MenuItem (string na, string descrip, double pric) {name = na; description = descrip; price = pric ;} string getName () {return name;} string getDescription () {return description;} double getPrice () {return price;} private: string name; string description; double price ;}; // class PancakeHouseMenu {public: PancakeHouseMenu () {addItem ("K & B's Breakfase", "pacakes with eggs", 2.99 ); addItem ("Buleberry Breakfase", "pacakes with buleberries", 3.99);} void addItem (string na, string descrip, double ric) {MenuItem menuItem (na, descrip, ric ); menuItems. push_back (menuItem);} listGetMenuItems () {return menuItems;} private: listMenuItems ;}; // class DinerMenu for lunch order {public: DinerMenu () {addItem ("Vegetarian BLT", "Bacon with lettuce", 2.99 ); addItem ("BLT", "Bacon with tomato", 3.99);} void addItem (string na, string descrip, double ric) {MenuItem menuItem (na, descrip, ric ); menuItems. push_back (menuItem);} vectorGetMenuItems () {return menuItems;} private: vectorMenuItems ;}; // you must call pancakeHouseMenu. getMenuItems () and // dinerMenu. getMenuItems () to obtain their meal order PancakeHouseMenu pancakeHouseMenu; listBreakfastItems = pancakeHouseMenu. getMenuItems (); DinerMenu dinerMenu; vectorLunchItem = dinerMenu. getMenuItems (); list: Iterator iter = breakfastItems. begin (); // when printing a new meal order, you need to traverse the menu items in the original meal order cyclically for (; iter! = BreakfastItems. end (); ++ iter) {MenuItem menuItem = * iter; cout <menuItem. getName () <"" <menuItem. getPrice () <"" <menuItem. getDescription () <endl ;}for (unsigned int I = 0; I
        
         

If there is another third restaurant, we need a third loop, which means we need to write a lot of repeated code. The solution uses the iterator mode.

UML design:


Programming implementation and execution results:

# Include
          
           
# Include
           
            
# Include
            
             
# Include
             
              
Using namespace std; // menu item class MenuItem {public: MenuItem () {} MenuItem (string na, string descrip, double pric) {name = na; description = descrip; price = pric;} string getName () {return name;} string getDescription () {return description;} double getPrice () {return price;} private: string name; string description; double price ;}; // Iterator base class Iterator {public: // whether there is a menu virtual bool hasNext () {throw std :: exception ("ERROR") ;}; // obtain the next menu virtual MenuItem next () {throw std: exception ("ERROR ");};}; // class PancakeHouseMenuIterator: public Iterator {public: PancakeHouseMenuIterator (list
              Item) {items = item; iter = items. begin ();} MenuItem next () {MenuItem menuItem = * iter; ++ iter; return menuItem;} bool hasNext () {if (iter = items. end () {return false;} else {return true;} private: listItems; list: Const_iterator iter;}; // lunch shop menu Iterator class DinerMenuIterator: public Iterator {public: DinerMenuIterator (vectorItem): position (0) {items = item;} MenuItem next () {MenuItem menuItem = items [position]; position = position + 1; return menuItem;} bool hasNext () {if (position> = items. size () {return false;} else {return true;} private: vectorItems; unsigned int position ;}; // meal ticket Base class Menu {public: // create the Iterator virtual Iterator * createIterator () {throw std :: exception ("ERROR") ;}}; // class PancakeHouseMenu: public Menu {public: PancakeHouseMenu () {addItem ("K & B's Breakfase ", "pacakes with eggs", 2.99); addItem ("Buleberry Breakfase", "pacakes with buleberries", 3.99);} // Add the void addItem (string na, string descrip, double ric) {MenuItem menuItem (na, descrip, ric); menuItems. push_back (menuItem);} // create the PancakeHouseMenuIterator Iterator * createIterator () {return new PancakeHouseMenuIterator (menuItems);} private: listMenuItems ;}; // class DinerMenu: public Menu {public: DinerMenu () {addItem ("Vegetarian BLT", "Bacon with lettuce", 2.99 ); addItem ("BLT", "Bacon with tomato", 3.99);} void addItem (string na, string descrip, double ric) {MenuItem menuItem (na, descrip, ric ); menuItems. push_back (menuItem);} Iterator * createIterator () {return new DinerMenuIterator (menuItems);} private: vectorMenuItems ;}; // waiter class Waitress {public: Waitress (Menu * p_PancakeHouseMenu, Menu * p_DinerMenu) {pPancakeHouseMenu = p_PancakeHouseMenu; pDinerMenu = p_DinerMenu ;} // print menu void printMenu () {Iterator * pPancakeHouseIterator = pPancakeHouseMenu-> createIterator (); Iterator * pDinerIterator = pDinerMenu-> createIterator (); cout <"Menu" <endl <"----" <
                     
                       HasNext () {MenuItem menuItem = (MenuItem) iter-> next (); cout <menuItem. getName () <"" <menuItem. getPrice () <"" <menuItem. getDescription () <endl ;}} private: Menu * pPancakeHouseMenu; Menu * pDinerMenu ;}; // client code int main () {Menu * pPancakeHouseMenu = new PancakeHouseMenu (); menu * pDinerMenu = new DinerMenu (); Waitress waitress (pPancakeHouseMenu, pDinerMenu); waitress. printMenu (); return 0 ;}
                     
             
            
           
          

Execution result:

Menu

----

BREAKFAST

K & B 'SBreakfase 2.99 pacakes with eggs

BuleberryBreakfase 3.99 pacakes with buleberries

LUNCH

VegetarianBLT 2.99 Bacon with lettuce

BLT 3.99 Bacon with tomato

Press any key to continue...

Application of Design Principles:

Design Principle: A class should have only one cause of change. This principle tells us to maintain a single responsibility for a class as much as possible. If a class has more than two reasons for change, this will increase the change rate of the class in the future.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.