1. 程式人生 > >使用泛型來建立匿名類

使用泛型來建立匿名類

interface Generator<T> {
    T next();
}

class Generators{
    public static <T> Collection<T> fill(Collection<T> coll, Generator<T> gen, int n){
        for(int i = 0; i < n; i++){
            coll.add(gen.next());
        }
        return coll;
    }
}

class Customer{
    private static long counter = 1;
    private final long id = counter++;
    //構造器private 不能直接建立物件
    private Customer(){}
    public String toString(){ return "Customer "+ id;}

    public static Generator<Customer> generator(){
        return new Generator<Customer>() {
            @Override
            public Customer next() {
                return new Customer();
            }
        };
    }
}

class Teller{
    private static long counter = 1;
    private final long id = counter++;
    private Teller(){};
    public String toString(){
        return "Teller "+ id;
    }

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

public class Main{
    public static void serve(Teller t, Customer c){
        System.out.println(t + " serves" + c );
    }
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        //Teller t = new Teller();            //沒有public構造方法
        Random rand = new Random(47);
        Queue<Customer> line = new LinkedList<Customer>();
        Generators.fill(line, Customer.generator(), 8);
        List<Teller> tellers = new ArrayList<Teller>();
        Generators.fill(tellers, Teller.generator(), 4);
        for(Customer c : line){
            serve(tellers.get(rand.nextInt(tellers.size())), c);
        }
    }
}

執行結果:

Teller 3 servesCustomer 1
Teller 2 servesCustomer 2
Teller 3 servesCustomer 3
Teller 1 servesCustomer 4
Teller 1 servesCustomer 5
Teller 3 servesCustomer 6
Teller 1 servesCustomer 7
Teller 2 servesCustomer 8