匿名内部类
泛型还可以使用于内部类和匿名内部类。
class Customer {
private static long counter = 1;
private final long id = counter++;
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 = new Generator<Teller>() {
@Override
public Teller next() {
return new Teller();
}
};
}
public class BankTeller {
public static void serve(Teller t, Customer c) {
System.out.println(t + " serves " + c);
}
public static void main(String[] args) {
Random rand = new Random(47);
Queue<Customer> line = new LinkedList<>();
Generators.fill(line, Customer.generator(), 15);
List<Teller> tellers = new ArrayList<>();
Generators.fill(tellers, Teller.generator, 4);
for (Customer c : line) {
serve(tellers.get(rand.nextInt(tellers.size())), c);
}
}
}
// Outputs
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
Teller 2 serves Customer 13
Teller 1 serves Customer 14
Teller 1 serves Customer 15
上面的Customer
和Teller
都通过使用匿名内部类实现了Generator
接口,并且他们都只有private
的构造器,这就意味着要想创建这两个类的对象,必须使用generator
方法。其中,Customer
类的generator()
方法每次调用都会返回一个新的Generator<Customer>
对象,但我们其实并不需要多个Generator
对象。这时,就可以像Teller
类一样,只创建一个public
的generator
对象。在main
方法中,这两种创建Generator
对象的方法在fill()
中都用到了。
由于Customer
中的generator()
方法,以及Teller
中的Generator
对象都声明成static
,所以它们都无法作为接口的一部分,因此不能用接口这种特定的惯用法来泛化这两者。尽管如此,它们在fill()
方法中都工作得很好。(//TODO 看不懂)
网友评论