我有一个通用接口。
public interface Consumer<E> {
public void consume(E e);
}
我有一个类需要使用两种不同的对象,因此我想做以下操作:
public class TwoTypesConsumer implements Consumer<Tomato>, Consumer<Apple>
{
public void consume(Tomato t) { ..... }
public void consume(Apple a) { ...... }
}
显然我不能这样做。
当然,我可以自己实现调度,例如:
public class TwoTypesConsumer implements Consumer<Object> {
public void consume(Object o) {
if (o instanceof Tomato) { ..... }
else if (o instanceof Apple) { ..... }
else { throw new IllegalArgumentException(...) }
}
}
但是我正在寻找编译时的类型检查和分派解决方案,这正是泛型提供的。
我能想到的最好的解决方案是定义单独的接口,例如:
public interface AppleConsumer {
public void consume(Apple a);
}
从功能上来说,我认为这个解决方案是可以的。只是过于啰嗦和丑陋。
有什么想法吗?