Câu hỏi của tôi không dễ giải thích khi sử dụng các từ, may mắn thay nó không quá khó để chứng minh. Vì vậy, hãy theo tôi:Làm thế nào để kết hợp chính xác generics và thừa kế để có được kết quả mong muốn?
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;
}
});
}
}
Về cơ bản, tôi muốn phương thức "quy trình" chung quy định loại thông số chung của đối tượng Lệnh. Mục đích là để có thể hạn chế việc triển khai CommandProcessor khác nhau đối với các lớp nhất định thực hiện giao diện Command và đồng thời có thể gọi phương thức quy trình của bất kỳ lớp nào thực hiện giao diện CommandProcessor và nó trả về đối tượng kiểu được chỉ định bởi parametarized Command đối tượng. Tôi không chắc chắn nếu lời giải thích của tôi là đủ rõ ràng, vì vậy xin vui lòng cho tôi biết nếu cần giải thích thêm. Tôi đoán, câu hỏi là "Liệu điều này có thể làm được không?" Nếu câu trả lời là "Không", đó là công việc tốt nhất (tôi nghĩ về một đôi vợ chồng, nhưng tôi muốn một số ý tưởng mới)
Không nên 'BasicCommand' triển khai' Command'? –
Touche, cố định. Cảm ơn vì đã bắt được! – Andrey