15.6 利用泛型构建复杂模型

在本例中,构建的是一个零售店,它包含走廊,货架,商品:

class Product{
    private final int id;
    private String description;
    private double price;

    public Product(int id, String description, double price) {
        this.id = id;
        this.description = description;
        this.price = price;
        toString();
    }

    @Override
    public String toString() {
        return "Product{" +
                "id=" + id +
                ", description='" + description + '\'' +
                ", price=" + price +
                '}';
    }

    public static Generator<Product> generator = new Generator<Product>() {
        private Random r = new Random(47);
        @Override
        public Product next() {
            return new Product(r.nextInt(1000),"Test",Math.round(r.nextDouble() * 1000 + 0.99) );
        }
    };
}
class Self extends ArrayList{
    Self(int nProdects){
        Generators.fill(this,Product.generator,nProdects);
    }
}

class Aisle extends ArrayList<Self>{
    Aisle(int nShelves ,int nProducts){
        IntStream.range(0,nShelves).forEach(i->add(new Self(nProducts)));
    }
}
class CheckoutStand{}
class Office{}

public class Store extends ArrayList<Aisle>{
    private List<CheckoutStand> checkouts = new ArrayList<>();
    private Office office = new Office();
    public Store(int nAsinle,int nShelves,int nProduect){
        IntStream.range(0,nAsinle).forEach(i->add(new Aisle(nShelves,nProduect)));
    }

    @Override
    public String toString() {
       StringBuilder sb = new StringBuilder();
       this.forEach(a-> {
           a.forEach(s -> {
               s.forEach(p -> {
                   sb.append(p);
                   sb.append("\n");
               });
           });
       });
       return sb.toString();
    }

    public static void main(String[] args) {
        System.out.println(new Store(14,5,10));
    }
}

正如我们在Store.toString 中看到的那样,其结果是许多层容器,但是他们是类型安全切容易管理的。组装这个模型十分容易。


猜你喜欢

转载自blog.csdn.net/perfect_red/article/details/80822609