public interface Component{}
public class AppManager {
public void doWork(){
SomeComponent comp = new SomeComponent ();
AddComponentToList(comp);
}
public void AddComponentToList(Component compo){
componentList.add(compo);
}
/* Give me the component I want. */
public Component getComponent(Component comp){
for (Component component : getComponentList()) {
if (component instanceof comp) {
return component;
}
}
}
private ArrayList<Component> componentList = new ArrayList<Component>();
}
public class SomeComponent implements component {
public void MyMethod() {
appManager.getComponent(SomeComponent );
}
public void setAppMnger(AppManager appm){
this.appManager = appm;
}
private AppManager appManager ;
}
在上面的代码中,AppMnger 有一个组件列表。组件相互通信。因此,如果一个组件想知道另一个组件实例,它会调用 AppMnger getComponent(comp) 方法。但是当我使用 instanceof 运算符时出现错误。我不希望每个组件都比较列表,但我想将该任务委托给 AppMnger,因为他是知道它创建的组件的人。艾米想?