Neo*_*ist 2 java constructor design-patterns
以下设计的目的是允许String值(实际上)子类化以启用许多将构建冲突的构造函数方法(例如,即使参数名称不同,方法签名也是相同的) .
请考虑以下(非功能性)设计:
Id接口(空标记接口)
public interface Id {}
Run Code Online (Sandbox Code Playgroud)
类接口(空标记接口)
public interface Classes {}
Run Code Online (Sandbox Code Playgroud)
标题界面(空标记界面)
public interface Title {}
Run Code Online (Sandbox Code Playgroud)
工具类
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"));
}
Run Code Online (Sandbox Code Playgroud)
该方法需要每个参数"type"的接口和从特定接口"type"到Object然后到String的向下转换/向上转换...
我对这种方法感到不舒服,我希望有一种设计模式可以减轻我对子类String的期望(仅用于构造方法区分的目的)......
我有一个可变方法,它采用任意的名称值对集合来提供固定参数构造函数的替代方法,但上面显示的构造函数是最常见的组合,因此为方便程序员,他们目前正在考虑提供...
谢谢!
考虑一下构造函数的外观,我建议你去掉它们并使用Builder模式:
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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
Tool tool = Tool.builder()
.withId("id")
.withClasses("classA, classB")
.build();
Run Code Online (Sandbox Code Playgroud)