Study Notes in Head First design mode-iterator mode + Combination Mode

Source: Internet
Author: User

The iterator mode is symbiotic with the set. Generally, as long as we implement a set, we need to provide the set iterator at the same time, just like the Collection in java, list, Set, Map, etc. These sets all have their own iterators. If we want to implement such a new container, we also need to introduce the iterator mode to implement an iterator for our container. ---- Question
Design ModeIterator mode: provides a method to access each element in an aggregate object sequentially 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.
Combination Mode: allows you to combine objects into a tree structure to display the "whole/part" layered structure. The combination allows the customer to process individual objects and object combinations in a consistent manner. Using the combination structure, we can apply the same operation to the combination and individual objects. In other words, in most cases, we can ignore the differences between object combinations and individual objects.
Design principlesSingle responsibility: one class should have only one cause of change.
Key PointsThe iterator allows access to aggregated elements without exposing their internal structure. The iterator encapsulates the traversal and aggregation work into an object. The iterator provides a common interface that allows us to traverse aggregated items. When we encode aggregated items, we can use the polymorphism mechanism. The combination mode allows customers to treat individual objects and composite objects equally. There are many design compromises when implementing a combination mode. You need to balance transparency and security as needed.
Model MatchingThe policy model encapsulates interchangeable phases and uses delegation to determine which adapter model is used to change one or more class interface iterator models to provide a way to traverse the set, without exposing the set, implementing the appearance model simplifies the interface combination model of a group class. The customer can treat the object set and individual objects equally as the observer model. When a State changes, allows a group of objects to be notified.
Iterator mode:

// Define the Iterator interface public interface Iterator {boolean hasNext (); Object next () ;}// implements implement the specific interface public class DinerMenuIterator implements Iterator {MenuItem [] items; int position = 0; public DinerMenuIterator (MenuItem [] items) {this. items = items;} public Object next () {MenuItem menuItem = items [position]; position = position + 1; return menuItem;} public boolean hasNext () {if (position> = items. length | it EMS [position] = null) {return false;} else {return true ;}} public class DinerMenu implements Menu {static final int MAX_ITEMS = 6; int numberOfItems = 0; menuItem [] menuItems; public DinerMenu () {menuItems = new MenuItem [MAX_ITEMS]; 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); add Item ("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);} public void addItem (String name, Stri Ng description, boolean vegetarian, double price) {MenuItem menuItem = new MenuItem (name, description, vegetarian, price); if (numberOfItems> = MAX_ITEMS) {System. err. println ("Sorry, menu is full! Can't add item to menu ");} else {menuItems [numberOfItems] = menuItem; numberOfItems = numberOfItems + 1 ;}// return the Iterator interface public Iterator createIterator () {return new DinerMenuIterator (menuItems);} // other menu methods here} package net. dp. iterator. dinermerger; public class Waitress {PancakeHouseMenu pancakeHouseMenu; DinerMenu dinerMenu; // In the constructor, the Waitress takes care of two menus public Waitress (inclupancakehousemenu, DinerMenu dinerMenu) {this. pancakeHouseMenu = pancakeHouseMenu; this. dinerMenu = dinerMenu;} public void printMenu () {// create an Iterator pancakeIterator = pancakeHouseMenu for each menu. createIterator (); Iterator dinerIterator = dinerMenu. createIterator (); System. out. println ("MENU \ n ---- \ nBREAKFAST"); // calls the reload printMenu () for each iterator to pass the iterator into printMenu (pancakeIterator); System. out. println ("\ nLUNCH"); printMenu (dinerIterator);} private void printMenu (Iterator iterator) {while (iterator. hasNext () {MenuItem menuItem = (MenuItem) iterator. next (); System. out. print (menuItem. getName () + ","); System. out. print (menuItem. getPrice () + "--"); System. out. println (menuItem. getDescription () ;}// other methods here}

Combination Mode:
// MenuComponent provides the default implementation of public abstract class MenuComponent {public void add (MenuComponent menuComponent) for each method {// All components must implement the MenuComponent interface, however, leaf nodes and composite nodes have different roles, so some methods may not be suitable for some node. In this case, sometimes you 'd better throw a runtime exception. Throw new partition ();} public void remove (MenuComponent menuComponent) {throw new UnsupportedOperationException ();} public MenuComponent getChild (int I) {throw new UnsupportedOperationException ();} public String getName () {throw new UnsupportedOperationException ();} public String getDescription () {throw new UnsupportedOperationException ();} public double getPrice () {throw new UnsupportedOperationException ();} public boolean isVegetarian () {throw new UnsupportedOperationException ();} public abstract Iterator
 
  
CreateIterator (); public void print () {throw new UnsupportedOperationException () ;}// first, expand the MenuComponent interface to implement the menu item public class MenuItem extends MenuComponent {String name; String description; boolean vegetarian; double price; public MenuItem (String name, String description, boolean vegetarian, double price) {this. name = name; this. description = description; this. vegetarian = vegetarian; this. price = price;} public String getName () {return name;} public String getDescription () {return description;} public double getPrice () {return price;} public boolean isVegetarian () {return vegetarian;} public Iterator
  
   
CreateIterator () {return new NullIterator ();} // For menu items, this method prints the complete menu item Entry public void print () {System. out. print ("" + getName (); if (isVegetarian () {System. out. print ("(v)");} System. out. println ("," + getPrice (); System. out. println ("--" + getDescription ();} // vv MenuItemCompositeV2Main} // implement the combination Menu public class Menu extends MenuComponent {// The Menu can have any number of children, all these children must belong to the MenuComponent ArrayList
   
    
MenuComponents = new ArrayList
    
     
(); String name; String description; public Menu (String name, String description) {this. name = name; this. description = description;} public void add (MenuComponent menuComponent) {menuComponents. add (menuComponent);} public void remove (MenuComponent menuComponent) {menuComponents. remove (menuComponent);} public MenuComponent getChild (int I) {return (MenuComponent) menuComponents. get (I) ;}public String getName () {return name;} public String getDescription () {return description;} public Iterator
     
      
CreateIterator () {return new CompositeIterator (menuComponents. iterator ();} public void print () {System. out. print ("\ n" + getName (); System. out. println ("," + getDescription (); System. out. println ("---------------------"); // use the Iterator to traverse all components Iterator
      
        Iterator = menuComponents. iterator (); while (iterator. hasNext () {MenuComponent menuComponent = iterator. next (); menuComponent. print () ;}} public class Waitress {MenuComponent allMenus; // you only need to hand over the top menu to the waiter for public Waitress (MenuComponent allMenus) {this. allMenus = allMenus;} public void printMenu () {allMenus. print ();} public void printVegetarianMenu () {Iterator
       
         Iterator = allMenus. createIterator (); System. out. println ("\ nVEGETARIAN MENU \ n ----"); while (iterator. hasNext () {MenuComponent menuComponent = iterator. next (); try {// we call the isVegetarian method of all menuComponent, but the Menu will throw an exception because they do not support this operation if (menuComponent. isVegetarian () {menuComponent. print () ;}} catch (UnsupportedOperationException e) {// If the menu component does not support this operation, we will ignore this exception .}}}} Package net. dp. composite. menuiterator; public class MenuTestDrive {public static void main (String args []) {// create all Menu MenuComponent pancakeHouseMenu = new MENU ("pancake house Menu", "Breakfast "); menuComponent dinerMenu = new Menu ("diner menu", "Lunch"); MenuComponent cafeMenu = new Menu ("cafe menu", "Dinner "); menuComponent dessertMenu = new Menu ("dessert menu", "Dessert of course! "); MenuComponent allMenus = new Menu (" all menus "," All menus combined "); // add each Menu to the top Menu by using the combined add method. add (pancakeHouseMenu); allMenus. add (dinerMenu); allMenus. add (cafeMenu); // add each menu item pancakeHouseMenu. add (new MenuItem ("K & B's Pancake Breakfast", "Pancakes with scrambled eggs, and toast", true, 2.99 )); // Add more menu items // once the entire Finance level is constructed, assign it to Waitress waitress = new Waitress (allMenus); waitress. printVegetarianMenu ();}}
       
      
     
    
   
  
 


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.