lundi 30 mars 2020

Correct implementation pattern in java: multiple classes inherit from abstract class but one method differs

I've tried to find a solution for my doubt in the forum but I haven't been able to.

On top I have an abtracts class Item. On a first depth level of inheritance I have ClickableItem and DraggableItem and them many items extend those 2 classes. Then I have a class View which contains many items (into an arraylist) and this class has 2 methods: onClick and onDrag.

What I am doing right now is to check on the onClick method all the items and if the item extends the ClickableItem, then call the onClick method of the item. Same thing for the onDrag method.

But I feel that this is not very good oop. The item object should know if it has to call that method or not, not the View class right? The View class should call a method which all the items should have in common and the items should decide whether to call onDrag or not.

Right now I have something like this:

public abstract class Item{
    int x, y;
    public Item(int x, int y){
        this.x = x;
        this.y = y;
    }
}

abstract class ClickableItem extends Item{
    protected boolean amIclicked(int x, int y);
    public ClickableItem(int mouseX, int mouseY){
        super(x, y);
    }
}

abstract class DraggableItem extends Item{
    protected boolean amIdragged(int x, int y);
    public ClickableItem(int mouseX, int mouseY){
        super(x, y);
    }
}

class ClickableImage extends ClickableItem{
    String imgRoute;
    public ClickableImage(int x, int y, String imgRoute){
        super(x, y);
        this.imgRoute = imgRoute;
    }
    public boolean amIclicked(int mouseX, int mouseY){
    }
}

class DraggableImage extends DraggableItem{
    String imgRoute;
    public DraggableImage(int x, int y, String imgRoute){
        super(x, y);
        this.imgRoute = imgRoute;
    }
    public boolean amIdragged(int mouseX, int mouseY){
    }
}

class View{
    ArrayList<Item> items;
    DraggableItem draggedItem;

    public View(){
        items = new ArrayList<Item>();
        items.add(new ClickableImage(200, 200));
        items.add(new DraggableImage(500, 500));
    }
    void onClick(int mouseX, int mouseY){
        for(Item it : items){
            if(ClickableItem.class.isAssignableFrom(it.getClass())){
                ((ClickableItem)it).amIclicked(mouseX, mouseY);
            }
        }
     }
     void onDrag(int mouseX, int mouseY){
         for(Item it : items){
             if(DraggableItem.class.isAssignableFrom(it.getClass())){
                 if(((DraggableItem)it).amIdragged(mouseX, mouseY)){
                     draggedItem = (DraggableItem)it;
                 }
             }
         }
     }
}

Aucun commentaire:

Enregistrer un commentaire