Vitali Melamud
Vitali Melamud

Reputation: 1397

Design of data accumulation while iterating a collection

I have a big collection of elements. I would like to iterate it and accumulate some specific values (let's say about 10 values). I wonder if there is a good way to do it SW design wise.

I would like to accumulate the data and later create a final object that consists of the accumulated data (immutable object). Is there a good design pattern for such purpose?

The "Builder" is not good here because I would like to change the values while iterating the collection.

Thanks a lot!

Upvotes: 1

Views: 301

Answers (2)

Erwin Bolwidt
Erwin Bolwidt

Reputation: 31279

You can use the Builder design pattern (I've linked one blog post but you can find plenty of information with Google).

This pattern is used when there are a lot of arguments in the constructors, which makes it cumbersome to invoke and maintain the constructor(s) in Java. It is especially used when you want to preserve invariants in the class that is being built (otherwise, it would be possible to configure the class using setter methods). One case in which this is true is when you have immutable objects, which is your case.

Upvotes: 2

JB Nizet
JB Nizet

Reputation: 691835

The builder pattern is what you're looking for. You store your accumulated data into a builder object and, when you're done, ask the builder to create the immutable object from everything it has accumulated.

Without a more concrete usecase from you, it's hard to give you a more concrete example.

But see this pattern in action here, for example.

Upvotes: 1

Related Questions