在不使用具有长参数列表的构造函数的情况下构建大的不可变对象 [英] Building big, immutable objects without using constructors having long parameter lists

查看:106
本文介绍了在不使用具有长参数列表的构造函数的情况下构建大的不可变对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些大的(超过3个字段)对象,它们可以而且应该是不可变的。每次遇到这种情况时,我倾向于使用长参数列表创建构造函数可恶。它感觉不对,难以使用且可读性受损。

I have some big (more than 3 fields) Objects which can and should be immutable. Every time I run into that case i tend to create constructor abominations with long parameter lists. It doesn't feel right, is hard to use and readability suffers.

如果字段是某种类似列表的集合类型,那就更糟了。一个简单的 addSibling(S s)可以简化对象的创建,但渲染对象是可变的。

It is even worse if the fields are some sort of collection type like lists. A simple addSibling(S s) would ease the object creation so much but renders the object mutable.

做什么你们在这种情况下使用吗?我在使用Scala和Java,但我认为只要语言是面向对象的,问题就是语言不可知。

What do you guys use in such cases? I'm on Scala and Java, but i think the problem is language agnostic as long as the language is object oriented.

我能想到的解决方案:


  1. 具有长参数列表的构造函数可憎

  2. 构建器模式

感谢您的输入!

推荐答案

嗯,您希望两者都更容易一旦创建了读取和不可变对象?

Well, you want both an easier to read and immutable object once created?

我认为流畅的界面正确完成会对你有帮助。

I think a fluent interface CORRECTLY DONE would help you.

它看起来像这样(纯粹的例子):

It would look like this (purely made up example):

final Foo immutable = FooFactory.create()
    .whereRangeConstraintsAre(100,300)
    .withColor(Color.BLUE)
    .withArea(234)
    .withInterspacing(12)
    .build();

我用粗体写了CORRECTLY DONE,因为大多数Java程序员都能说得流利接口错误并用构建对象所需的方法污染它们的对象,这当然是完全错误的。

I wrote "CORRECTLY DONE" in bold because most Java programmers get fluent interfaces wrong and pollute their object with the method necessary to build the object, which is of course completely wrong.

诀窍是只有build()方法实际上创建了一个Foo (因此你Foo可以是不可变的)。

The trick is that only the build() method actually creates a Foo (hence you Foo can be immutable).

FooFactory.create() whereXXX( ..) withXXX(..)都创建其他东西。

FooFactory.create(), whereXXX(..) and withXXX(..) all create "something else".

其他东西可能是FooFactory,这是一种方法....

That something else may be a FooFactory, here's one way to do it....

You FooFactory看起来像这样:

You FooFactory would look like this:

// Notice the private FooFactory constructor
private FooFactory() {
}

public static FooFactory create() {
    return new FooFactory();
}

public FooFactory withColor( final Color col ) {
    this.color = color;
    return this;
}

public Foo build() {
    return new FooImpl( color, and, all, the, other, parameters, go, here );
}

这篇关于在不使用具有长参数列表的构造函数的情况下构建大的不可变对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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