泛型的作用——构建复杂模型

构建TupleList

泛型的一个重要的好处就是可以简单安全地创建复杂的模型。

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);
        }
    }
}

上面的代码创建了一个元组列表。
尽管这看上去有些冗长(特别在迭代器的创建),但是最终还是没用过多的代码就得到了一个相当强大的数据结构。

产品模型

下面的示例展示了使用泛型类型来构建复杂模型是多么地简单,即使每一个类都是作为一个块构建的,但是其整个还是包含许多部分,本例中,构建的模型是一个零售店,它包含走廊,货架和商品。

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类中一层套着一层,是一种多层容易,但是它们是一种类型安全并且可管理的。
可以看到,使用泛型来创建这样的一个容器是十分简易的。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容