你有界面。
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
,而是传递Structure
。 Structure
不是 ArrayList
它是 Group
的后代。这个结构内部有它自己的list
。使用它自己的 assemble()
方法实现。
关于java - 使用接口(interface)将一个数组列表传递给包装类中的另一个数组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18762995/