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

看《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适配器是否有用?谢谢!

大家讲道理
大家讲道理

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

répondre à tous(0)
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!