15.3 泛型接口_Coffee

public interface Generator {

    T next();

}
public class Coffee {

    private static long counter = 0;
    private final long id = counter++;

    @Override
    public String toString() {
        return getClass().getSimpleName() + " " + id;
    }
}
public class Americano extends Coffee {
}
public class Breve extends Coffee {
}
public class Cappuccino extends Coffee {
}
public class Latte extends Coffee {
}
public class Mocha extends Coffee {
}
  • 实现 Iterable 接口的类可以用 foreach 循环遍历;
  • Random random = new Random(47)一旦给了种子,random.nextInt(5)就给出的结果就是一样的;
public class CoffeeGenerator implements Generator, Iterable {

    private Class[] types = {Americano.class, Breve.class, Cappuccino.class, Latte.class, Mocha.class};

    private int size;

    private static Random random = new Random(47);

    public CoffeeGenerator() {}

    public CoffeeGenerator(int size) {
        this.size = size;
    }

    @Override
    public Coffee next() {
        try {
            return (Coffee)types[random.nextInt(types.length)]
               .newInstance();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    class CoffeeIterator implements Iterator {

        int count = size;

        @Override
        public boolean hasNext() {
            return count > 0;
        }

        @Override
        public Coffee next() {
            count --;
            return CoffeeGenerator.this.next();
        }

    }

    @Override
    public Iterator iterator() {
        return new CoffeeIterator();
    }

}

class CoffeeGeneratorClient {

    public static void main(String[] args) {
        CoffeeGenerator coffeeGenerator = new CoffeeGenerator();
        for(int i = 0; i < 5; i++)
            System.out.println(coffeeGenerator.next());
        for(Coffee c : new CoffeeGenerator(5))
            System.out.println(c);
    }

}

输出

Latte 0
Americano 1
Latte 2
Breve 3
Breve 4
Mocha 5
Latte 6
Americano 7
Cappuccino 8
Cappuccino 9

你可能感兴趣的:(15.3 泛型接口_Coffee)