OOPS (Design Patterns) [closed]

2020-04-09 03:04发布

hey, hi i want put limit on object creation means a class can have at most suppose 4 objects not more than that how to achieve this?

6条回答
欢心
2楼-- · 2020-04-09 03:39

One way to achieve is the Singleton Design pattern, Whenever we make a call to create an instance, check the count of the instance which are already created, if the instance count is already reached 4, then use the same instance for your application. TO have a count, Creat Static Int Counter = 0; and keep incrementing it to get the results.

查看更多
兄弟一词,经得起流年.
3楼-- · 2020-04-09 03:47

Try modifying the Singleton pattern. You can use a count variable. You'll need to keep the Constructor private to have control over the no. of instances.

查看更多
Anthone
4楼-- · 2020-04-09 03:48

The simplest way to do this would be to have a class level attribute called "count", and in your constructor, just make sure that "count" isn't above a certain number.

//pseudocode
class foo
  static count = 0

  def constructor()
    if count < 4
      //create object
    else
      //there are too many!
查看更多
我欲成王,谁敢阻挡
5楼-- · 2020-04-09 03:49

This is short code snippest that will give the above result in c#

sealed class clsInstance
    {
        public static int count = 0;
        private static readonly clsInstance inst = new clsInstance();
        clsInstance()
        {

        }

        public static clsInstance Inst
        {
            get
            {
                if (count < 4)
                {

                    Console.WriteLine("object : " + count);
                    count++;
                    return inst;
                }
                return null;
            }
        }


    }

   class MainClass
   {
       public static void Main(String[] args)
       {
           clsInstance c1 = clsInstance.Inst;
           clsInstance c2 = clsInstance.Inst;
           clsInstance c3 = clsInstance.Inst;
           clsInstance c4 = clsInstance.Inst;
           Console.ReadLine();
           clsInstance c5 = clsInstance.Inst;
           Console.ReadLine();
       }
   }
查看更多
Luminary・发光体
6楼-- · 2020-04-09 03:49

One approach is using an object factory that creates at most 4 instances. It's an interesting need... Would an object pool serve the same need?

查看更多
Bombasti
7楼-- · 2020-04-09 03:51

You can count the numbers of instances created by using a static class property to store the count. This can either be done in the class constructor or you can make use of a factory pattern. It is a bit difficult to answer this more precisely without knowing the target language.

查看更多
登录 后发表回答