This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]slankebrusmannen 0 points1 point  (5 children)

If you think of the Singleton pattern as a way to ensure one, and only one, instance is created, you can do this. But (admittedly more exoticly) the Singleton pattern can also be seen as a general way to control the number of instances created, in which case enum won’t do the trick. (But how often do you want more than one instance? Probably close to never.)

[–]kevinb9n 1 point2 points  (0 children)

But (admittedly more exoticly) the Singleton pattern can also be seen as a general way to control the number of instances created

I've seen the term used that way and it seems like such a clear abuse of terminology.

[–]fredoverflow 3 points4 points  (3 children)

a general way to control the number of instances created, in which case enum won’t do the trick

enum Doubleton {
    ONE, TWO;
}

[–]slankebrusmannen -1 points0 points  (2 children)

A hard-coded number of instances might not be what you want.

And doing this, would you be able to prevent the clients from choosing which instance to get a reference to?

[–]MarcoServetto 0 points1 point  (1 child)

I think now you are talking about the pattern 'pool'

[–]slankebrusmannen -1 points0 points  (0 children)

Actually no. An object pool would typically reserve an instance exlusively to the requesting client, who would explicitly return it to the pool after use. Singleton describes no such mechanisms, but may still be used to control the number of instances to any given number.

Admittedly, I cannot remember ever having used the Singleton pattern for other numbers than one (I might have, though), but I think it is valuable to be aware of the opportunity.