简体   繁体   中英

Is passing class in java as argument good choice for getting information about concrete implementation of interface?

i have problem with interface's method. It's rather design problem than programming implementation problem.

I tried to implement Composite Design Pattern in my project. Firstly, I was using Enum to distinguish different kind of elements (getElementType was main method to ensure what information is inside the object - there were a lot of different Tree elements). This solution was terrible... I know

I deleted enum and created many smaller classes, used inheritance and implemented concrete method from my interface for each Object.

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();

But sometimes I want to know, which class this object is, so I created method and added to Actionable interface

public Actionable doSomething(Class classOfElement){

    if(classOfElement.equals(ElemLeaf.class){

        return this;

    }
    else{

        return new ElemLeaf();

    }
}

I don't know if it is a good design principle to put Class as parameter or it is terrible choice. Maybe I should change my classes and interfaces composition to avoid this situation.

I hope that I made myself clear. These examples are not from my project, but they are similiar.

I would just make TreeElem an Actionable which would delegate the action call to it's children. That way the caller doesn't have to care wheter it's children nodes are leafs or not.

If for some reason you have to handle concrete node types in many different ways when walking the tree then you may want to check the Visitor Pattern .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM