具有大参数的Java构造函数或Java

具有大参数的Java构造函数或Java

本文介绍了具有大参数的Java构造函数或Java bean getter / setter方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法确定哪种方法更适合创建具有大量字段(10+)(所有必需)的getter / setter的构造方法的对象。构造函数至少你强制设置所有的字段。 Java Bean更容易看到设置了哪些变量,而不是一个巨大的列表。
Builder模式似乎并不适合这里的所有字段是强制性的建筑商要求你把所有必需的参数在构建器构造。

I can't decide which approach is better for creating objects with a large number of fields (10+) (all mandatory) the constructor approach of the getter/setter. Constructor at least you enforce that all the fields are set. Java Beans easier to see which variables are being set instead of a huge list.The builder pattern DOES NOT seem suitable here as all the fields are mandatory and the builder requires you put all mandatory parameters in the builder constructor.

谢谢,
D

Thanks,D

推荐答案

更好的方法(恕我直言)是使用某种建设者:

The better approach (imho) is to use some kind of builder:

MyClass a = new MyClassBuilder().blah("blah").foo("foo").doStuff().toMyClass();

其中MyClass仍然但一个更可读的创作比10参数的构造函数。

where MyClass is still immutable but has a far more readable creation than a constructor with 10 arguments.

这也被称为流畅界面。乔希布洛赫指的是这的。

This is also called a fluent interface. Josh Bloch refers to this in Effective Java.

这篇关于具有大参数的Java构造函数或Java bean getter / setter方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 14:32