mercredi 28 octobre 2015

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.

Aucun commentaire:

Enregistrer un commentaire