假设我有两个接口和一个行为类:
public interface Creable {
public boolean belongsToSystem();
public List<Creable> getCreatedItems();
}
public interface HasDependencies {
public void createDependencies();
public void generateDependents();
}
public class CreableBehavior {
private Creable creableObject;
public CreableBehavior(Creable creableObject) {
this.creableObject = creableObject;
}
public boolean hasBeenCreated() {
return !creableObject.belongsToSystem() && !creableObject.getCreatedItems().contains(createdObject);
}
而这段代码:
Creable includedTab = new AdempiereTab(getIncluded_Tab_ID(),
creableElements);
if (!new CreableBehavior(includedTab).hasBeenCreated) {
includedTab.createDependencies();
includedTab.getCreatedItems().add(includedTab);
includedTab.generateDependents();
}
AdempiereTab 实现了 Creable 和 HasDependencies。问题是我需要同时使用接口 Creable 和 HasDependencies。
我应该这样投射:
if (!new CreableBehavior(includedTab).hasBeenCreated) {
((AdempiereTab)includedTab).createDependencies();
includedTab.getCreatedItems().add(includedTab);
((AdempiereTab)includedTab).generateDependents();
}
或者我应该创建一个新的接口 CreableWithDependencies 来扩展这两个接口并使用那个接口吗?
谢谢。
编辑:回答,我应该扩展接口,因为我不想依赖于实现类型。将它们结合起来可以让我使用具有相同代码的多种类型。