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
You'll simply need to use the factory pattern with a counter of the number of instances created, after which the factory method will throw an exception/return null.
Example:
public class Foobar
{
private static int numInstances = 0;
public static Foobar CreateFoobar()
{
if (numInstances++ < 10)
{
return new Foobar();
}
return null;
}
protected Foobar()
{
...
}
}
The above method will work perfectly well for a single-instance application, but for a multi-instance application, you'll probably want to use a semaphore (an implementation exists in System.Threading), which is intended for precisely this sort of situation (limiting access to resources/objects). It gets around the problem of multiple instances of the class being requested almost simultaneously and the count checks failing.