下面java代码的CollectionData适配器是否有用
大家讲道理
大家讲道理 2017-04-17 13:09:20
0
0
369

看《java编程思想》遇到的问题:在讲容器的时候,提出一种用生成器来填充容器的方法:
代码如下:

javapublic class CollectionData<T> extends ArrayList<T>{
    public CollectionData(Generator<T> gen, int quantity){
        for(int i=0; i<quantity; i++){
            add(gen.next());
        }
    }

    public static <T> CollectionData<T> list(Generator<T> gen, int quantity){
        return new CollectionData(gen, quantity);
    }
}

class Government implements Generator<String> {
  String[] foundation = ("strange women lying in ponds " +
    "distributing swords is no basis for a system of " +
    "government").split(" ");
  private int index;
  public String next() { return foundation[index++]; }
}

public class CollectionDataTest {
  public static void main(String[] args) {
    Set<String> set = new LinkedHashSet<String>(
      new CollectionData<String>(new Government(), 15));
    // Using the convenience method:
    set.addAll(CollectionData.list(new Government(), 15));
    System.out.println(set);
  }
}

我理解这是一种适配器设计模式的应用,通过 new CollectionData(new Government(), 15)可以一次生成给定数量的某个类的对象。 但是不知道为什么要以这么一种繁琐的方式. 举个例子
我想生成10个Coffee对象..

javapublic class CopyOfCollectionDataTest {
  public static void main(String[] args) {
        Set<Coffee> set2 = new LinkedHashSet<Coffee>();
        int  i = 10;
        while(i !=0){
        set2.add(new Coffee());
        i--;
    }

觉得这段代码已经足够,如果生成其他类型的对象只需要修改Set类型参数即可呀。
所以问题是上面的CollectionData适配器是否有用?谢谢!

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

全員に返信(0)
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!