從頭認識java-13.5 利用泛型構建複雜模型

來源:互聯網
上載者:User

從頭認識java-13.5 利用泛型構建複雜模型

這一章節我們來展示一下怎樣利用泛型構建複雜模型?

1.元組列表

我們之前已經說過元組是一個複雜的模型,可以返回多個物件。

 

package com.ray.ch11;import java.util.ArrayList;public class Test {public ArrayList

 

上面的代碼我們通過元組來實現一個比較複雜的模型。

我們下面再引用另外一個例子,一個商店。

 

2.商店

這個商店由辦公區、前台、銷售區組成,而且銷售區由若干貨架組成,貨架上面又需要放置多種貨物。

 

package com.ray.ch11;import java.util.ArrayList;import java.util.Collection;import java.util.Random;public class Store extends ArrayList {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 generator = new Generator() {@Overridepublic Product next() {Random random = new Random();int id = random.nextInt();return new Product(id, test- + id, random.nextDouble());}};@Overridepublic String toString() {return produce id:  + id +  name:  + name +  price:  + price;}}interface Generator {public T next();}class Generators {public static  Collection fill(Collection collection,Generator generator, int num) {for (int i = 0; i < num; i++) {collection.add(generator.next());}return collection;}}class Shelf extends ArrayList {/** *  */private static final long serialVersionUID = 1L;public Shelf(int produceNum) {Generators.fill(this, Product.generator, produceNum);}}class SaleZone extends ArrayList {/** *  */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裡面建立產生器。

 

總結:這一章節主要是展示一下怎樣利用泛型構建複雜模型。

 


 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.