Limit instances creation of a class?

前端 未结 6 1636
暖寄归人
暖寄归人 2021-01-11 16:15

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

6条回答
  •  情歌与酒
    2021-01-11 16:39

    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.

提交回复
热议问题