在 Java 中管理具有多个参数的构造函数 [英] Managing constructors with many parameters in Java

查看:33
本文介绍了在 Java 中管理具有多个参数的构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我们的一些项目中,有一个类层次结构,它会在链中向下添加更多参数.在底部,一些类最多可以有 30 个参数,其中 28 个刚刚被传递到超级构造函数中.

In some of our projects, there's an class hierarchy that adds more parameters as it goes down the chain. At the bottom, some of the classes can have up to 30 parameters, 28 of which are just being passed into the super constructor.

我承认通过 Guice 之类的工具使用自动化 DI 会很好,但由于某些技术原因,这些特定项目仅限于 Java.

I'll acknowledge that using automated DI through something like Guice would be nice, but because of some technical reasons, these specific projects are constrained to Java.

按类型按字母顺序组织参数的约定行不通,因为如果一个类型被重构(您为参数 2 传入的 Circle 现在是一个 Shape),它可能会突然乱序.

A convention of organizing the arguments alphabetically by type doesn't work because if a type is refactored (the Circle you were passing in for argument 2 is now a Shape) it can suddenly be out of order.

这个问题可能很具体,并且充满了如果那是你的问题,你在设计层面做错了"的批评,但我只是在寻找任何观点.

This question might be to specific and fraught with "If that's your problem, you're doing it wrong at a design level" criticisms, but I'm just looking for any viewpoints.

推荐答案

构建器设计模式可能会有所帮助.考虑下面的例子

The Builder Design Pattern might help. Consider the following example

public class StudentBuilder
{
    private String _name;
    private int _age = 14;      // this has a default
    private String _motto = ""; // most students don't have one

    public StudentBuilder() { }

    public Student buildStudent()
    {
        return new Student(_name, _age, _motto);
    }

    public StudentBuilder name(String _name)
    {
        this._name = _name;
        return this;
    }

    public StudentBuilder age(int _age)
    {
        this._age = _age;
        return this;
    }

    public StudentBuilder motto(String _motto)
    {
        this._motto = _motto;
        return this;
    }
}

这让我们可以编写像

Student s1 = new StudentBuilder().name("Eli").buildStudent();
Student s2 = new StudentBuilder()
                 .name("Spicoli")
                 .age(16)
                 .motto("Aloha, Mr Hand")
                 .buildStudent();

如果我们省略了一个必填字段(大概名称是必需的),那么我们可以让 Student 构造函数抛出异常.它让我们拥有默认/可选参数,而无需跟踪任何类型的参数顺序,因为这些调用的任何顺序都将同样有效.

If we leave off a required field (presumably name is required) then we can have the Student constructor throw an exception. And it lets us have default/optional arguments without needing to keep track of any kind of argument order, since any order of those calls will work equally well.

这篇关于在 Java 中管理具有多个参数的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆