java - 使用接口(interface)将一个数组列表传递给包装类中的另一个数组列表

标签 java

你有界面。

public interface Group {
    public void assemble();
}

您有两个实现该接口(interface)的类。

public class Block implements Group {

    public void assemble() {
        System.out.println("Block");
    }
}

public class Structure implements Group {
  // Collection of child groups.
  private List<Group> groups = new ArrayList<Group>();

  public void assemble() {
    for (Group group : groups) {
      group.assemble();
    }
  }

  // Adds the group to the structure.
  public void add(Group group) {
    groups.add(group);
  }

  // Removes the group from the structure.
  public void remove(Group group) {
    groups.remove(group);
  }
}

创建对象后:

Structure structure = new Structure();
Structure structure1 = new Structure();

并在结构体实例中填充ArrayList:

structure1.add(new Block());
structure1.add(new Block());

您可以传递:structure.add(struct1)

但是当您将一个 ArrayList 单独传递给另一个时,您必须使用 addAll 方法:

List<Group> groups = new ArrayList<Group>();
List<Group> groups1 = new ArrayList<Group>();
groups1.addAll(groups);
<小时/>

我的问题是为什么这有效?

<小时/>

示例来自:http://javapapers.com/design-patterns/composite-design-pattern/

最佳答案

没有传递ArrayList,而是传递StructureStructure 不是 ArrayList 它是 Group 的后代。这个结构内部有它自己的list。使用它自己的 assemble() 方法实现。

关于java - 使用接口(interface)将一个数组列表传递给包装类中的另一个数组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18762995/

相关文章:

java - 从 lib 文件夹中的类扩展 WAR 中的抽象类

具有 PHP 和爆炸 war 支持的 Java 应用程序服务器

java - 监控程序背后的逻辑

java - Solr 。奇怪的方面搜索结果

java - 为什么这个算法在追踪时没有意义?

java - 单击按钮时 Android 应用程序关闭(在自定义注册页面上)

java - Java的SDK中接口(interface)常量声明示例

java - 使用 Java 配置和 Spring Security 3.2 的安全方法注释

Java 读取文件获得了领先的 BOM [  ]

java - MySQL 和 JDBC : What is the safest way to manage multiple schemas?