제 질문은 단어를 사용하여 설명하기가 쉽지 않습니다. 다행히도 설명하기가 어렵지 않습니다. 그래서 나와 함께 곰 :제네릭과 상속을 적절하게 혼합하여 원하는 결과를 얻는 방법은 무엇입니까?
public interface Command<R>
{
public R execute();//parameter R is the type of object that will be returned as the result of the execution of this command
}
public abstract class BasicCommand<R> implements Command<R>
{
}
public interface CommandProcessor<C extends Command<?>>
{
public <R> R process(C<R> command);//this is my question... it's illegal to do, but you understand the idea behind it, right?
}
//constrain BasicCommandProcessor to commands that subclass BasicCommand
public class BasicCommandProcessor<C extends BasicCommand<?>> implements CommandProcessor<C>
{
//here, only subclasses of BasicCommand should be allowed as arguments but these
//BasicCommand object should be parameterized by R, like so: BasicCommand<R>
//so the method signature should really be
// public <R> R process(BasicCommand<R> command)
//which would break the inheritance if the interface's method signature was instead:
// public <R> R process(Command<R> command);
//I really hope this fully illustrates my conundrum
public <R> R process(C<R> command)
{
return command.execute();
}
}
public class CommandContext
{
public static void main(String... args)
{
BasicCommandProcessor<BasicCommand<?>> bcp = new BasicCommandProcessor<BasicCommand<?>>();
String textResult = bcp.execute(new BasicCommand<String>()
{
public String execute()
{
return "result";
}
});
Long numericResult = bcp.execute(new BasicCommand<Long>()
{
public Long execute()
{
return 123L;
}
});
}
}
기본적으로, 나는 일반적인 "프로세스"방법은 Command 개체의 일반적인 매개 변수의 유형을 지시하고 싶습니다. 목표는 CommandProcessor의 다른 구현을 Command 인터페이스를 구현하는 특정 클래스로 제한 할 수 있고 동시에 CommandProcessor 인터페이스를 구현하는 모든 클래스의 프로세스 메서드를 호출하고 해당 클래스의 process 객체를 반환 할 수있게하는 것입니다. 매개 변수화 된 Command 개체. 내 설명이 명확한 지 확실하지 않으므로 추가 설명이 필요한 경우 알려 주시기 바랍니다. 나는 "이게 가능할 수 있을까?"라는 질문을 던집니다. 대답이 "아니오"일 경우 가장 좋은 해결 방법이 될 것입니다. (내 생각으로는 몇 가지 생각이 들지만 신선한 아이디어가 필요합니다)
'BasicCommand'가'Command'를 구현하지 않아야합니까? –
Touche, fixed. 그것을 잡아 주셔서 감사합니다! – Andrey