OnJava8-Examples/generics/BankTeller.java

62 lines
1.8 KiB
Java
Raw Normal View History

2015-09-07 11:44:36 -06:00
// generics/BankTeller.java
2015-12-15 11:47:04 -08:00
// (c)2016 MindView LLC: see Copyright.txt
2015-11-15 15:51:35 -08:00
// We make no guarantees that this code is fit for any purpose.
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
2016-01-25 18:05:55 -08:00
// A very simple bank teller simulation
2015-06-15 17:47:35 -07:00
import java.util.*;
2016-01-25 18:05:55 -08:00
import onjava.*;
2015-06-15 17:47:35 -07:00
class Customer {
private static long counter = 1;
private final long id = counter++;
@Override
public String toString() { return "Customer " + id; }
}
class Teller {
private static long counter = 1;
private final long id = counter++;
@Override
public String toString() { return "Teller " + id; }
2016-01-25 18:05:55 -08:00
}
class Bank {
private List<BankTeller> tellers = new ArrayList<>();
public void put(BankTeller bt) { tellers.add(bt); }
2015-06-15 17:47:35 -07:00
}
public class BankTeller {
public static void serve(Teller t, Customer c) {
System.out.println(t + " serves " + c);
}
public static void main(String[] args) {
2016-01-25 18:05:55 -08:00
// Demonstrate create():
RandomList<Teller> tellers =
Suppliers.create(RandomList::new, Teller::new, 4);
// Demonstrate fill():
List<Customer> customers = Suppliers.fill(
new ArrayList<>(), Customer::new, 12);
customers.forEach(c -> serve(tellers.select(), c));
// Demonstrate assisted latent typing:
Bank bank = Suppliers.fill(
new Bank(), Bank::put, BankTeller::new, 3);
// Can also use second version of fill():
List<Customer> customers2 = Suppliers.fill(
new ArrayList<>(), List::add, Customer::new, 12);
2015-06-15 17:47:35 -07:00
}
2015-09-07 11:44:36 -06:00
}
/* Output:
2015-06-15 17:47:35 -07:00
Teller 3 serves Customer 1
Teller 2 serves Customer 2
Teller 3 serves Customer 3
Teller 1 serves Customer 4
Teller 1 serves Customer 5
Teller 3 serves Customer 6
Teller 1 serves Customer 7
Teller 2 serves Customer 8
Teller 3 serves Customer 9
Teller 3 serves Customer 10
Teller 2 serves Customer 11
Teller 4 serves Customer 12
2015-09-07 11:44:36 -06:00
*/