我正在编写一个流畅的API来配置和实例化一系列"消息"对象.我有一个消息类型的层次结构.
为了能够在使用流畅的API时访问子类的方法,我使用泛型来参数化子类,并使所有流畅的方法(以"with"开头)返回泛型类型.请注意,我省略了流体方法的大部分主体; 其中有很多配置.
public abstract class Message<T extends Message<T>> {
protected Message() {
}
public T withID(String id) {
return (T) this;
}
}
Run Code Online (Sandbox Code Playgroud)
具体子类同样重新定义泛型类型.
public class CommandMessage<T extends CommandMessage<T>> extends Message<CommandMessage<T>> {
protected CommandMessage() {
super();
}
public static CommandMessage newMessage() {
return new CommandMessage();
}
public T withCommand(String command) {
return (T) this;
}
}
public class CommandWithParamsMessage extends
CommandMessage<CommandWithParamsMessage> {
public static CommandWithParamsMessage newMessage() {
return new CommandWithParamsMessage();
}
public CommandWithParamsMessage withParameter(String paramName,
String paramValue) {
contents.put(paramName, …Run Code Online (Sandbox Code Playgroud) 我正面临这个问题中描述的问题,但想找到一个没有所有演员和@SuppressWarning注释的解决方案(如果可能的话).
一个更好的解决方案是建立在引用的解决方案之上:
此处提供的解决方案将根据标准评分为2分.Bounty用大多数积分去解决方案,或者如果有多个积分,那么"最优雅的"积分将达到2分.
我有2个类,每个类在所有函数中返回自己:
public class Parent{
public Parent SetId(string id){
...
return this
}
}
public class Child : Parent{
public Child SetName(string id){
...
return this
}
}
Run Code Online (Sandbox Code Playgroud)
我想启用这种API:
new Child().SetId("id").SetName("name");
Run Code Online (Sandbox Code Playgroud)
SetName因为无法访问SetId的回报Parent,并SetName为上Child.
怎么样?