我有一个mixin,我想将其用于几种类型的请求,例如CatRequest和DogRequest。我在mixin中创建了一个方法,该方法根据请求的类型和响应中的设置从请求中检索某些详细信息。检查实例并像下面这样强制转换是否是理想的选择?还是有更好的方法使用泛型来处理此问题?
default <T> Response setAnimalDetails(final T request, final Response response) {
Animal animal = new Animal();
if (request instanceof CatRequest) {
CatRequest catRequest = (CatRequest) request;
animal.setType(catRequest.getType());
animal.setAge(catRequest.getAge());
animal.setWhiskerLength(catRequest.getWhiskerLength());
} else if (request instanceof DogRequest) {
DogRequest dogRequest = (DogRequest) request;
animal.setType(dogRequest.getAnimalType());
animal.setAge(dogRequest.getAge());
// since dogs don't have whiskers, DogRequest doesn't have a whiskers field
}
response.setAnimal(animal);
return response;
}
答案 0 :(得分:1)
Mixin和泛型似乎是一种通过继承来实现某些目的的inherit回方式。
interface AnimalMaker {
Animal createAnimal();
}
class CatRequest implements AnimalMaker {
@Override
public Animal createAnimal() {
Animal animal = new Animal();
animal.setType(getType());
animal.setAge(getAge());
animal.setWhiskerLength(getWhiskerLength());
return animal;
}
}
class DogRequest implements AnimalMaker {
@Override
public Animal createAnimal() {
Animal animal = new Animal();
animal.setType(getAnimalType());
animal.setAge(getAge());
return animal;
}
}
这样,您无需使用setAnimalDetails
方法,只需将您的请求声明为AnimalMaker
并执行
response.setAnimal(request.createAnimal());
最好制作Animal
之类的Cat
和Dog
之类,并为请求类键入参数,但是您可以自己做。< / p>