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

查看:268
本文介绍了在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.

我会承认使用自动DI通过像Guice这样的东西会很好,但由于某些技术原因,这些特定的项目都受限于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();

如果我们省略一个必填字段(大概是名字是必需的)那么我们可以让学生构造函数抛出例外。
它允许我们拥有默认/可选参数,而无需跟踪任何类型的参数顺序,因为这些调用的任何顺序都可以正常工作。

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天全站免登陆