Is passing class in java as argument good choice for getting information about concrete implementation of interface?
我对接口的方法有疑问。这是设计问题,而不是编程实现问题。
我试图在我的项目中实现Composite Design Pattern。首先,我使用Enum来区分不同类型的元素(getElementType是确保对象内部包含哪些信息的主要方法-有很多不同的Tree元素)。这个解决方案太糟糕了...我知道
我删除了枚举并创建了许多较小的类,使用继承并从我的接口为每个Object实现了具体方法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | TreeElem elem; // ... etc if(elem.getElementType()==ElemType.LEAF){ elem.action(); } public interface Actionable{ void action(); } public class ElemLeaf extends TreeElem implements Actionable{ public void action(){ // something funny haha } } Actionable elem = new ElemLeaf(); elem.action(); |
但是有时候我想知道这个对象是哪个类,所以我创建了方法并将其添加到Actionable接口
1 2 3 4 5 6 7 8 9 10 11 12 13 | public Actionable doSomething(Class classOfElement){ if(classOfElement.equals(ElemLeaf.class){ return this; } else{ return new ElemLeaf(); } } |
我不知道将Class作为参数是一个好的设计原则,还是一个糟糕的选择。也许我应该更改类和接口的组成以避免这种情况。
我希望我能说清楚。这些示例并非来自我的项目,但它们是相似的。
我只是将
如果由于某种原因在走树时必须以许多不同的方式处理具体的节点类型,那么您可能要检查"访问者模式"。