Iterator (Iterator mode) -- (supermarket manager)

Source: Internet
Author: User

This Iterator is used by the cashier. [Html] package patterns. actions. iterator; public interface IteratorList {boolean isEmpty (); // whether [hasNext ()] Object nextMerchandise (); // merchandise: item} [java] package patterns. actions. iterator;/*** check items at the cashier * @ author one **/public class IteratorCheck implements IteratorList {private Supermarket shop; private int total = 0; private int current = 0; iteratorCheck (Supermarket shop) {this. shop = shop; this. total = shop. size (); this. current = 0 ;}@ Override public boolean isEmpty () {return this. current <this. total ;}@ Override public Object nextMerchandise () {if (this. current <this. total) return this. shop. take (this. current ++); return null;} [java] package patterns. actions. iterator;/*** basic Shopping elements * @ author one **/public interface Shopping {public void buy (Object obj ); // buy a new product [add] public IteratorList iteratorList (); // check [iterator]} [java] package patterns. actions. iterator; import java. util. arrayList; import java. util. list;/*** supermarkets provide specific Shopping environments ** @ author one **/public class Supermarket implements Shopping {private List cart = new ArrayList (); // The cart is used as the container @ Override public void buy (Object obj) {cart. add (obj); // put the item to the shopping cart} @ Override public IteratorList iteratorList () {return new IteratorCheck (this);} public int size () {return this. cart. size ();} public Object take (int current) {if (current <this. cart. size () return this. cart. get (current); return null;} [java] package patterns. actions. iterator; public class Client {/*** @ param args */public static void main (String [] args) {Shopping cart = new Supermarket (); cart. buy ("Cola"); cart. buy ("juice"); cart. buy ("sour plum"); IteratorList check = cart. iteratorList (); while (check. isEmpty () {System. out. println (check. nextMerchandise () ;}} output: [html] cola

Related Article

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.