15.3 泛型接口_Coffee

本文介绍了一个使用Java实现的咖啡生成器类,该类实现了Generator和Iterable接口,能够生成多种类型的咖啡对象,包括美式咖啡、拿铁等。通过Random类的种子设定,确保了每次运行生成的咖啡类型序列相同,便于测试和复现。文章还展示了如何使用foreach循环遍历生成的咖啡对象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public interface Generator<T> {

    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<Coffee>, Iterable<Coffee> {

    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<Coffee> {

        int count = size;

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

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

    }

    @Override
    public Iterator<Coffee> 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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值