英文:
Java creating a generic class that implement another generic interface with constraints
问题
界面要实现的部分:
public interface Message {
}
public interface Handles<T extends Message> {
void handle(T message);
}
具体实现部分:
public class EnforcementHandler<T extends Handles<T extends Message>> {
}
意外的限制
在Java中是否可能出现这种模式?
英文:
Interface to be implemented:
public interface Message {
}
public interface Handles<T extends Message> {
void hanlde(T message);
}
Concrete implementation:
public class EnforcementHandler<T extends Handles<T extends Message>> {
}
Unexpected bound
Is this pattern possible in Java?
答案1
得分: 4
你必须将它写成 EnforcementHandler<M extends Message, T extends Handles<M>>
。
英文:
You must write it as EnforcementHandler<M extends Message, T extends Handles<M>>
.
答案2
得分: 0
你的EnforcementHandler
的确切责任是模糊的。根据其名称中的“Handler”部分,我认为它的责任是“处理”事务。所以,根据我理解,这似乎是一个适当的实现。
public class EnforcementHandler<M extends Message> implements Handler<M> {
public void handle(M msg) {
out.printf("%1$70s%n ", msg.read());
}
}
...
Message msg = () -> "Friends of space, how are you all? Have you eaten yet? Come visit us if you have time.";
EnforcementHandler
handler.handle(msg);
...
将这条友好消息打印到stdout
。友好消息如下:
Friends of space, how are you all? Have you eaten yet? Come visit us if you have time.
英文:
What the exact responsibility of your EnforcementHandler
is, is ambiguous.
Going by the „Handler“ part of its name, suggests to me that its responsibility is to „handle“ things. So this seems an appropriate implementation to my understanding…
public class EnforcementHandler<M extends Message> implements Handler<M>{
public void handle( M msg ) { out.printf( "%1$70s%n ", msg.read( ) ); }
}
This demo shows how it could be used…
...
Message msg = ( ) -> "Friends of space, how are you all? Have you eaten yet? Come visit us if you have time.";
EnforcementHandler< Message > handler = new EnforcementHandler< >( );
handler.handle( msg );
...
…Printing this friendly message to stdout
…
Friends of space, how are you all? Have you eaten yet? Come visit us if you have time.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论