I am using C#. I have created a class which can be included in any c#.net project (desktop or web based), but I want that only 10 objects will be created in that application of my class. If object instances created more than 10 then it should give an error or simple will not work.
There can be two situations,
In both situations it must through error if more than 10 instances of my class is created in the application.
This question was asked by my teacher, he told me to search for the answer on internet, I tried but no where found any solution for this problem, I haven't heard that we can limit objects?
Is it possible, if yes then how?
Thanks
Keep a static variable with the number of instances created. Increment that number with each construction of the object. Make the object IDisposable and decrement that number on each call to Dispose(). If you want it to be thread-safe, use Interlocked.Increment() and Interlocked.Decrement() to change the value of this variable instead of ++ and --.
I believe that you want some form of the multiton pattern.
The multiton pattern is a variation on the singleton pattern, but that allows for n instances of an object. Much like how the singleton class has a static variable to hold the single instance, the multiton is often implemented with a static array or map of instances, depending on how you want to access the instances - arrays only allow for numerical access, but by using a map, you could provide String keys to your instances, making them named.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With