Simple store-original

Java Primer
Incremental J2EE
by Vince Huston
Listing 1. Starting Point.


// Purpose.  Starting point

import java.util.*;

class Item {
   private String name;
   public Item( String na ) { name = na; }
   public String toString() { return name; }
}

interface IStore {
   ArrayList getItems();
   String    placeOrder( ArrayList list );
}

class StoreImpl implements IStore {
   private ArrayList itemList = new ArrayList();

   public StoreImpl() {
      itemList.add( new Item( "Design Patterns by GOF" ) );
      itemList.add( new Item( "Using UML and Patterns" ) );
      itemList.add( new Item( "C++ for Deadend Careers" ) );
      itemList.add( new Item( "Java for Resume Inflation" ) );
      itemList.add( new Item( "Practical Java" ) );
   }
   public ArrayList getItems() { return itemList; }
   public String placeOrder( ArrayList list ) {
      StringBuffer sb = new StringBuffer();
      sb.append( "The following items were ordered:\n" );
      for (Iterator it = list.iterator(); it.hasNext(); ) {
         sb.append( "   " );
         sb.append( itemList.get( ((Integer)it.next()).intValue() ) );
         sb.append( '\n' );
      }
      return sb.toString();
}  }

class Factory {
   public static IStore createStore() { return new StoreImpl(); }
}



import java.util.*;
import java.io.*;

public class StoreClient {
   public static void main( String[] args ) throws IOException {
      BufferedReader in = new BufferedReader(
                             new InputStreamReader( System.in ) );
      ArrayList theChoices = new ArrayList();
      int choice;

      // Get a Store object somehow (create, load, look up)
      IStore theStore = Factory.createStore();

      // Download and present the list of current titles
      ArrayList theItems = theStore.getItems();

      System.out.println( "Select from (0 when done):" );
      Iterator it = theItems.iterator();
      for (int i=1; it.hasNext(); i++)
         System.out.println( "   " + i + " - " + it.next() );

      // Solicit the customer's choices
      while (true) {
         System.out.print( "Choice: " );
         if ((choice = Integer.parseInt( in.readLine() )) == 0) break;
         theChoices.add( new Integer( choice-1 ) );
      }

      // Place the order with the Store,
      //    AND, print the returned confirmation statement
      System.out.println( theStore.placeOrder( theChoices ) );
}  }

// Select from (0 when done):
//    1 - Design Patterns by GOF
//    2 - Using UML and Patterns
//    3 - C++ for Deadend Careers
//    4 - Java for Resume Inflation
//    5 - Practical Java
// Choice: 1
// Choice: 3
// Choice: 5
// Choice: 0
// The following items were ordered:
//    Design Patterns by GOF
//    C++ for Deadend Careers
//    Practical Java