構(gòu)建TupleList
泛型的一個重要的好處就是可以簡單安全地創(chuàng)建復(fù)雜的模型。
public class TupleList<A, B, C, D> extends ArrayList<FourTuple<A, B, C, D>> {
public static void main(String[] args) {
TupleList<Vehicle, Amphibian, String, Integer> t1 = new TupleList<>();
t1.add(TupleTest.h());
t1.add(TupleTest.h());
for (FourTuple<Vehicle, Amphibian, String, Integer> i : t1) {
System.out.println("i = " + i);
}
}
}
上面的代碼創(chuàng)建了一個元組列表。
盡管這看上去有些冗長(特別在迭代器的創(chuàng)建),但是最終還是沒用過多的代碼就得到了一個相當(dāng)強大的數(shù)據(jù)結(jié)構(gòu)。
產(chǎn)品模型
下面的示例展示了使用泛型類型來構(gòu)建復(fù)雜模型是多么地簡單,即使每一個類都是作為一個塊構(gòu)建的,但是其整個還是包含許多部分,本例中,構(gòu)建的模型是一個零售店,它包含走廊,貨架和商品。
class Product {
private final int id;
private String desc;
private double price;
public Product(int id, String desc, double price) {
this.id = id;
this.desc = desc;
this.price = price;
System.out.println(toString());
}
@Override
public String toString() {
return id + ": " + desc + " , price: $" + price;
}
public void priceChange(double change) {
price += change;
}
public static Generator<Product> generator = new Generator<Product>() {
private Random rand = new Random(47);
@Override
public Product next() {
return new Product(rand.nextInt(1000), "Test", Math.round(rand.nextDouble() * 1000.0) + 0.99);
}
};
}
// 貨架
class Shelf extends ArrayList<Product> {
public Shelf(int nProducts) {
Generators.fill(this, Product.generator, nProducts);
}
}
// 走廊
class Aisle extends ArrayList<Shelf> {
public Aisle(int nShelves, int nProducts) {
for (int i = 0; i < nShelves; i++) {
add(new Shelf(nProducts));
}
}
}
// 收銀臺
class CheckoutStand {
}
// 辦公
class Office {
}
public class Store extends ArrayList<Aisle> {
private ArrayList<CheckoutStand> checkouts = new ArrayList<>();
private Office office = new Office();
public Store(int nAisles, int nShelves, int nProducts) {
for (int i = 0; i < nAisles; i++) {
add(new Aisle(nShelves, nProducts));
}
}
@Override
public String toString() {
StringBuilder result = new StringBuilder();
for (Aisle a : this) {
for (Shelf s : a) {
for (Product p : s) {
result.append(p);
result.append("\n");
}
}
}
return result.toString();
}
public static void main(String[] args) {
System.out.println(new Store(14, 5, 10));
}
}
// Outputs
258: Test , price: $400.99
861: Test , price: $160.99
868: Test , price: $417.99
207: Test , price: $268.99
551: Test , price: $114.99
...
上面的Store類中一層套著一層,是一種多層容易,但是它們是一種類型安全并且可管理的。
可以看到,使用泛型來創(chuàng)建這樣的一個容器是十分簡易的。