I've been looking into the visitor pattern and I've finally understood how to use it. But now I'm trying to take it one step further and I want to decouple the visitor logic from the objects. Here's what I'm trying to accomplish
keep in mind, I'm also using the strategy pattern for the makeNoise()
method:
public class Animal {
Public INoise noise;
public void makeNoise() {
noise.makeNoise();
}
}
public class Dog { }
public class Cat { }
-
public interface INoise() {
public void makeNoise();
}
public class DogNoise implements INoise {
public void makeNoise() {
println("dog noise");
}
}
public class CatNoise implements INoise {
public void makeNoise() {
println("cat noise");
}
}
-
public interface IAnimalVisitor {
public DogNoise dispatchNoise(Dog dog);
public CatNoise dispatchNoise(Cat cat);
public INoise dispatchNoise(Class<? extends Animal> class1);
}
public class IAnimVisitDispatcher implements IAnimalVisitor {
public DogNoise dispatchNoise(Dog dog) {
return new DogNoise();
}
public CatNoise dispatchNoise(Cat cat) {
return new CatNoise();
}
public INoise dispatchNoise(Class<? extends Animal> class1) {
return dispatchNoise(class1);
}
}
so at the end theres the dispatchNoise
method that accepts anything that extends Animal
as a parameter, and then redirects to the correct dispatchNoise
method to return the right type of noise.
so what I'm trying to do is (pseudo code):
Animal a = new Dog();
//this calls the third dispatchNoise method
//dispatchNoise(Class<? extends Animal> class1)
a.noise = IAnimVisitDispatcher.dispatchNoise(a.getClass());
but this isn't working, I'm just getting a stack overflow error.
What is the correct way of doing this, and another question would be, should I even be doing this? is this bad practice?
Aucun commentaire:
Enregistrer un commentaire