您的位置:首页 > 编程语言 > Java开发

从头认识java-13.5 利用泛型构建复杂模型

2015-12-14 00:00 519 查看
这一章节我们来展示一下怎样利用泛型构建复杂模型?

1.元组列表

我们之前已经说过元组是一个复杂的模型,可以返回多对象。

package com.ray.ch11;

import java.util.ArrayList;

public class Test {
public ArrayList<Tuple<A, B, C>> test() {
ArrayList<Tuple<A, B, C>> list = new ArrayList<Tuple<A, B, C>>();
for (int i = 0; i < 10; i++) {
list.add(new Tuple<A, B, C>(new A(), new B(), new C()));
}
return list;
}

public static void main(String[] args) {
new Test().test();
}
}

class A {
}

class B {
}

class C {
}

@SuppressWarnings("hiding")
class Tuple<A, B, C> {
public final A a;
public final B b;
public final C c;

public Tuple(A a, B b, C c) {
this.a = a;
this.b = b;
this.c = c;
}
}


上面的代码我们通过元组来实现一个比较复杂的模型。

我们下面再引用另外一个例子,一个商店。

2.商店

这个商店由办公区、前台、销售区组成,而且销售区由若干货架组成,货架上面又需要放置多种货物。

package com.ray.ch11;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Random;

public class Store extends ArrayList<SaleZone> {
private Office office = new Office();
private CheckOut checkOut = new CheckOut();

public Store(int saleZoneNum, int shelfNum, int produceNum) {
for (int i = 0; i < saleZoneNum; i++) {
add(new SaleZone(shelfNum, produceNum));
}
}

public static void main(String[] args) {
new Store(1, 2, 5);
}
}

class Product {
private int id = 0;
private String name = "";
private double price = 0.0;

public Product(int id, String name, double price) {
this.id = id;
this.name = name;
this.price = price;
System.out.println(toString());
}

public static Generator<Product> generator = new Generator<Product>() {
@Override
public Product next() {
Random random = new Random();
int id = random.nextInt();
return new Product(id, "test-" + id, random.nextDouble());
}
};

@Override
public String toString() {
return "produce id: " + id + " name: " + name + " price: " + price;
}
}

interface Generator<T> {
public T next();
}

class Generators {
public static <T> Collection<T> fill(Collection<T> collection,
Generator<T> generator, int num) {
for (int i = 0; i < num; i++) {
collection.add(generator.next());
}
return collection;
}
}

class Shelf extends ArrayList<Product> {
/**
*
*/
private static final long serialVersionUID = 1L;

public Shelf(int produceNum) {
Generators.fill(this, Product.generator, produceNum);
}
}

class SaleZone extends ArrayList<Shelf> {
/**
*
*/
private static final long serialVersionUID = 1L;

public SaleZone(int shelfNum, int produceNum) {
for (int i = 0; i < shelfNum; i++) {
add(new Shelf(produceNum));
}
}
}

class Office {
}

class CheckOut {
}


大家可能理解上面的代码会比较复杂一点,我解释一下:

1.第一个难度在于生成器,如果读了前面章节也许会简单一点。其实这里使用生成器,主要是为了抽象出一个比较通用的生成器,如果是一般的代码,我们可以在product里面直接返回一个produceList,这样的代码看上去也许会好很多。

2.Generators,主要是抽象出往容器填充数据的通用性代码。

3.里面有几个类都直接继承了ArrayList,这里是为了在构造器的时候就可以直接调用add方法,不用在构造一次ArrayList,如果按照平常的习惯,也许我们会自己建立一个ArrayList,然后往里面填充数据就算了

4.使用匿名内部类在product里面创建生成器。

总结:这一章节主要是展示一下怎样利用泛型构建复杂模型。

这一章节就到这里,谢谢。

-----------------------------------

目录
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: