Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit instances creation of a class?

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,

  1. I'll included myclass.cs file in any project or
  2. I'll bundle my class in a DLL and then include it in any application

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

like image 650
djmzfKnm Avatar asked Aug 09 '09 14:08

djmzfKnm


2 Answers

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 --.

like image 54
Dave Markle Avatar answered Oct 09 '22 00:10

Dave Markle


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.

like image 41
Thomas Owens Avatar answered Oct 09 '22 00:10

Thomas Owens