OOPS (design patterns)

Hey hello, I want the restriction on creating an object to mean that the class can at least assume that 4 objects are nothing more than how to do this?

+4
source share
6 answers

One approach uses a factory object that creates no more than 4 instances. This is an interesting need ... Can a pool of objects serve the same need?

+10
source

, static class . , factory. , .

+3

. count. , Constructor , no. .

+3

- Singleton Design, , , , , 4, . , Creat Static Int Counter = 0; , .

+1

- , "count", , "count" .

//pseudocode
class foo
  static count = 0

  def constructor()
    if count < 4
      //create object
    else
      //there are too many!
0

, #

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();
       }
   }
0

All Articles