以下设计的目的是允许 String 值(实际上)被子类化,以建立许多冲突的构造函数方法(例如,即使参数名称不同,方法签名也将相同)有所不同)。
请考虑以下(非功能性)设计:
Id 接口(interface)(空标记接口(interface))
public interface Id {}
类接口(interface)(空标记接口(interface))
public interface Classes {}
标题界面(一个空的标记界面)
public interface Title {}
工具类
public Tool(Id id) throws Exception
{
this.span = new Span();
this.span.addAttribute(new Attribute(Attribute.ID, (String)((Object) id)));
}
public Tool(Classes classes) throws Exception
{
this.span = new Span();
this.span.addAttribute(new Attribute(Attribute.CLASS, (String)((Object) classes)));
}
public Tool(Title title) throws Exception
{
this.span = new Span();
this.span.addAttribute(new Attribute(Attribute.TITLE, (String)((Object) title)));
}
public Tool(Id id, Classes classes, Title title) throws Exception
{
this.span = new Span();
this.span.addAttribute(new Attribute(Attribute.ID, (String)((Object) id)));
this.span.addAttribute(new Attribute(Attribute.CLASS, (String)((Object) classes)));
this.span.addAttribute(new Attribute(Attribute.TITLE, (String)((Object) title)));
}
public void Test() throws Exception
{
Tool hammer = new Tool((Id)((Object)"hammer"));
Tool poweredTool = new Tool((Classes)((Object)"tool powered"));
Tool tool = new Tool((Id)((Object)"invention"), (Classes)((Object)"tool powered"), (Title)((Object)"define a new tool"));
}
该方法需要每个参数“类型”有一个接口(interface),以及从特定接口(interface)“类型”到对象然后到字符串的向下转换/向上转换...
我对这种方法感到不舒服,我希望有一种设计模式可以减轻我对 String 进行子类化的愿望(仅用于构造函数方法区分的目的)...
我有一个可变参数方法,它采用名称值对的任意集合来提供固定参数构造函数的替代方案,但上面显示的构造函数是最常见的组合,因此为了方便程序员,目前正在考虑使用它们所提供的...
谢谢!
最佳答案
考虑到你的构造函数的外观,我建议你摆脱它们并使用 Builder pattern相反:
class Tool {
private Tool() { // Preventing direct instantiation with private constructor
this.span = new Span();
}
... // Tool class code
public static Builder builder() {
return new Builder();
}
public static class Builder {
private final Tool tool = new Tool();
public Builder withId(String id) {
tool.span.addAttribute(new Attribute(Attribute.ID, id));
return this;
}
... // other methods in the same manner
public Tool build() {
// Add some validation if necessary
return tool;
}
}
}
用法:
Tool tool = Tool.builder()
.withId("id")
.withClasses("classA, classB")
.build();
关于Java 构造函数(反模式)父类(super class) String,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31173955/