Java 构造函数(反模式)父类(super class) String

标签 java design-patterns constructor

以下设计的目的是允许 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/

相关文章:

design-patterns - MVC 中的业务逻辑

vb.net - 静态局部变量是不好的做法吗?

java - 如何从给定的 java 类创建 UML 图?

c++ - 为什么所有现有的 C++ 编译器都不支持继承构造函数?

java - "aggregate-oriented domain"意味着什么(谈到基于 Spring 的应用程序)?

java - Hibernate uuid生成和mysql uuid函数uuid()

java - 是否有可能找出一个值是否在数组列表中存在两次?

c# - 数据访问对象模式如何提高性能?

javascript - oop 行为类似于构造函数参数类型的类

java - mongodb 2.6+中的批量操作可以用作缓冲区/队列吗?