How to make a Java class that implements one interface with two generic types?

匿名 (未验证) 提交于 2019-12-03 02:44:02

问题:

I have a generic interface

public interface Consumer {     public void consume(E e); } 

I have a class that consumes two types of objects, so I would like to do something like:

public class TwoTypesConsumer implements Consumer, Consumer {    public void consume(Tomato t) {  .....  }    public void consume(Apple a) { ...... } } 

Apparently I can't do that.

I can of course implement the dispatch myself, e.g.

public class TwoTypesConsumer implements Consumer {    public void consume(Object o) {       if (o instanceof Tomato) { ..... }       else if (o instanceof Apple) { ..... }       else { throw new IllegalArgumentException(...) }    } } 

But I am looking for the compile-time type-checking and dispatching solution that generics provide.

The best solution I can think of is to define separate interfaces, e.g.

public interface AppleConsumer {    public void consume(Apple a); } 

Functionally, this solution is OK, I think. It's just verbose and ugly.

Any ideas?

回答1:

Consider encapsulation:

public class TwoTypesConsumer {     private TomatoConsumer tomatoConsumer = new TomatoConsumer();     private AppleConsumer appleConsumer = new AppleConsumer();      public void consume(Tomato t) {          tomatoConsumer.consume(t);     }      public void consume(Apple a) {          appleConsumer.consume(a);     }      public static class TomatoConsumer implements Consumer {         public void consume(Tomato t) {  .....  }     }      public static class AppleConsumer implements Consumer {         public void consume(Apple a) {  .....  }     } } 

If creating these static inner classes bothers you, you can use anonymous classes:

public class TwoTypesConsumer {     private Consumer tomatoConsumer = new Consumer() {         public void consume(Tomato t) {         }     };      private Consumer appleConsumer = new Consumer() {         public void consume(Apple a) {         }     };      public void consume(Tomato t) {         tomatoConsumer.consume(t);     }      public void consume(Apple a) {         appleConsumer.consume(a);     } } 


回答2:

Because of type erasure you can't implement the same interface twice (with different type parameters).



回答3:

Here's a possible solution based on Steve McLeod's one:

public class TwoTypesConsumer {     public void consumeTomato(Tomato t) {...}     public void consumeApple(Apple a) {...}      public Consumer getTomatoConsumer() {         return new Consumer() {             public void consume(Tomato t) {                 consumeTomato(t);             }         }     }      public Consumer getAppleConsumer() {         return new Consumer() {             public void consume(Apple a) {                 consumeApple(t);             }         }     } } 

The implicit requirement of the question was Consumer and Consumer objects that share state. The need for Consumer, Consumer objects comes from other methods that expect these as parameters. I need one class the implement them both in order to share state.

Steve's idea was to use two inner classes, each implementing a different generic type.

This version adds getters for the objects that implement the Consumer interface, which can then be passed to other methods expecting them.



回答4:

At least, you can make a small improvement to your implementation of dispatch by doing something like the following:

public class TwoTypesConsumer implements Consumer { 

Fruit being an ancestor of Tomato and Apple.



回答5:

just Stumbled upon this. It just happened, that I had the same Problem, but I solved it in a different way: I just created a new Interface like this

public interface TwoTypesConsumer extends Consumer{     public void consume(B b); } 

unfortunately, this is considered as Consumer and NOT as Consumer against all Logic. So you have to create a small Adapter for the second consumer like this inside your class

public class ConsumeHandler implements TwoTypeConsumer{      private final Consumer consumerAdapter = new Consumer(){         public void consume(B b){             ConsumeHandler.this.consume(B b);         }     };      public void consume(A a){ //...     }     public void conusme(B b){ //...     } } 

if a Consumer is needed, you can simply pass this, and if Consumer is needed just pass consumerAdapter



回答6:

You cannot do this directly in one class as the class definition below cannot be compiled due to erasure of generic types and duplicate interface declaration.

class TwoTypesConsumer implements Consumer, Consumer {   // cannot compile  ... } 

Any other solution for packing the same consume operations in one class requires to define your class as:

class TwoTypesConsumer { ... } 

which is pointless as you need to repeat/duplicate the definition of both operations and they won't be referenced from interface. IMHO doing this is a bad small and code duplication which I'm trying to avoid.

This might be an indicator also that there is too much responsibility in one class to consume 2 different objects (if they aren't coupled).

However what I'm doing and what you can do is to add explicit factory object to create connected consumers in the following way:

interface ConsumerFactory {      Consumer createAppleConsumer();      Consumer createTomatoConsumer(); } 

If in reality those types are really coupled (related) then I would recommend to create an implementation in such way:

class TwoTypesConsumerFactory {      // shared objects goes here      private class TomatoConsumer implements Consumer {         public void consume(Tomato tomato) {             // you can access shared objects here         }     }      private class AppleConsumer implements Consumer {         public void consume(Apple apple) {             // you can access shared objects here         }     }       // It is really important to return generic Consumer here     // instead of AppleConsumer. The classes should be rather private.     public Consumer createAppleConsumer() {         return new AppleConsumer();     }      // ...and the same here     public Consumer createTomatoConsumer() {         return new TomatoConsumer();     } } 

The advantage is that the factory class knows both implementations, there is a shared state (if needed) and you can return more coupled consumers if needed. There is no repeating consume method declaration which aren't derived from interface.

Please note that each consumer might be independent (still private) class if they aren't completely related.

The downside of that solution is a higher class complexity (even if this can be a one java file) and to access consume method you need one more call so instead of:

twoTypesConsumer.consume(apple) twoTypesConsumer.consume(tomato) 

you have:

twoTypesConsumerFactory.createAppleConsumer().consume(apple); twoTypesConsumerFactory.createTomatoConsumer().consume(tomato); 

To summarize you can define 2 generic consumers in one top-level class using 2 inner classes but in case of calling you need to get first a reference to appropriate implementing consumer as this cannot be simply one consumer object.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!