4

Is there a realisation of a Singleton-like pattern which allows to create more than one instance (e.g 5 instances and no more). I guess it will be called Multiton Pattern. Thanks in advance

8
  • Technically this is possible; not sure how common it actually is in practice. Dec 5, 2011 at 19:07
  • So... something like a threadpool? Dec 5, 2011 at 19:08
  • i sense a little contradiction where you want to create multiple objects and you want it to be thread safe? what s the purpose if you dont allow each thread to get their instances and you dont want singleton?
    – DarthVader
    Dec 5, 2011 at 19:10
  • 1
    Might be a better question if you ask from the use-case. Dec 5, 2011 at 19:12
  • 2
    I found an article in Wikipedia, it seems there is a formal pattern en.wikipedia.org/wiki/Multiton_pattern
    – user824249
    Dec 5, 2011 at 19:21

3 Answers 3

6

It sounds like you're trying to perform some kind of object pooling?

If so, here's a solution I found with a quick Google search. http://www.codeproject.com/KB/cs/DotNetObjectPool.aspx

If I'm wrong, and you have a legit reason for limiting the number of instances, here's another SO question addressing this very pattern: Limit instances creation of a class?

2
  • Thank you! It just a question from my last interview.
    – user824249
    Dec 5, 2011 at 19:09
  • It's possible, but I can't really conceive of a reason why you'd limit the number, without the purpose to pooling instances for reuse. Dec 5, 2011 at 19:11
3

The pattern is called an Object Pool Pattern.

1

There is no such functionality out of the box. However, you can use Semaphore to synchronize the maximum count of resources, which are acquired and freed.

From the other hand you can use a usual Monitor to synchronize access to some variable, which will hold the currently created number of instances.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.