15.5 匿名内部类

package chapter15._5;

import chapter15._3.coffee.Generator;

public class Customer {

    private static long counter = 1;

    private final long id = counter++;

    private Customer() {}

    @Override
    public String toString() {
        return "Customer{" +
                "id=" + id +
                '}';
    }

    public static Generator generator() {
        return new Generator() {
            @Override
            public Customer next() {
                return new Customer();
            }
        };
    }
    
}
package chapter15._5;

import chapter15._3.coffee.Generator;

public class Teller {

    private static long counter = 1;

    private final long id = counter++;

    private Teller() {}

    @Override
    public String toString() {
        return "Teller{" +
                "id=" + id +
                '}';
    }

    public static Generator generator = new Generator() {
        @Override
        public Teller next() {
            return new Teller();
        }
    };

}
package chapter15._5;

import chapter15._4._3.Generators;

import java.util.*;

public class BankTeller {

    public static void serve(Teller t, Customer c) {
        System.out.println(t + " serves " + c);
    }

    public static void main(String[] args) {
        Random random = new Random(47);

        Queue line = new LinkedList();
        Generators.fill(line, Customer.generator(), 15);

        List tellers = new ArrayList();
        Generators.fill(tellers, Teller.generator, 4);

        for(Customer c : line)
            serve(tellers.get(random.nextInt(tellers.size())), c);
    }
}

输出

Teller{id=3} serves Customer{id=1}
Teller{id=2} serves Customer{id=2}
Teller{id=3} serves Customer{id=3}
Teller{id=1} serves Customer{id=4}
Teller{id=1} serves Customer{id=5}
Teller{id=3} serves Customer{id=6}
Teller{id=1} serves Customer{id=7}
Teller{id=2} serves Customer{id=8}
Teller{id=3} serves Customer{id=9}
Teller{id=3} serves Customer{id=10}
Teller{id=2} serves Customer{id=11}
Teller{id=4} serves Customer{id=12}
Teller{id=2} serves Customer{id=13}
Teller{id=1} serves Customer{id=14}
Teller{id=1} serves Customer{id=15}

你可能感兴趣的:(15.5 匿名内部类)