vendredi 24 novembre 2023

Java : generics, inheritance and best design

I have a basic processing interface :

public interface Processing<T> {
    void appendTo(T t);
}

And this inheritance tree :

public class Animal {
}

public class Dog extends Animal {
    public void forDog() {}
}

public class Cat extends Animal {
    public forCat() {}
}

It's about processing animals. I have two solutions. Which one is the best pattern ?

SOLUTION A (with generics) :

public abstract class AbstractProcessing<T extends Animal> implements Processing<T> {
    protected void internalAppend() {}
}

public class CatProcssing extends AbstractProcessing<Cat>{

    @Override
    public void appendTo(Cat cat) {
        cat.forCat();
        internalAppend();
    }
}

public class DogProcessing extends AbstractProcessing<Dog>{
    
    @Override
    public void appendTo(Dog dog) {
        dog.forDog();
        internalAppend();
    }
}

SOLUTION B :

public class AnimalProcessing implements Processing<Animal>{
    @Override
    public void appendTo(Animal animal) {
        if (animal instanceof Cat cat) {
            cat.forCat();
        } else if (animal instanceof Dog dog) {
            dog.forDog();
        } else {
            throw new IllegalArgumentException();
        }
        internalAppend();
    }

    private void internalAppend() { }
}

Aucun commentaire:

Enregistrer un commentaire