Can factory methods return multiple instances?
Asked Answered
U

3

6

It is a factory method if it returns an instance of a class but is it a factory method if it returns multiple (an array of) instances?

Urushiol answered 19/2, 2011 at 9:28 Comment(0)
O
6

If you need it to return multiple instances, then do it, regardless of how it is called. I would say it is indeed a factory method, but this doesn't matter that much.

Perhaps you can have a factory method for returning a single instance, and then another one that calls the first one multiple times.

Outfall answered 19/2, 2011 at 9:31 Comment(0)
W
3

If T is the type you want to create, yours is a Factory Method of T[], so yes, it's still a Factory Method, but not of T :-) (by T[] I mean an array of T, or the equivalent of your language)

Wretch answered 19/2, 2011 at 9:33 Comment(0)
P
1

Yes, you can even get more exotic:

int pipe(int fildes[2]);

The pipe() function shall create a pipe and place two file descriptors, one each into the arguments fildes[0] and fildes[1], that refer to the open file descriptions for the read and write ends of the pipe.

This is a factory which "returns" (using an out parameter and actual return value for an error code) two different objects corresponding to both ends of a pipe.

Don't get too hung up on the name "factory method" or even on design patterns, for that matter. Design patterns are useful because they give a common name to what we see every day, and then point out various common pitfalls or considerations – not because we need to strictly mold our code to some name.

Peplos answered 19/2, 2011 at 9:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.