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?
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?
, static class . , factory. , .
. count. , Constructor , no. .
- Singleton Design, , , , , 4, . , Creat Static Int Counter = 0; , .
- , "count", , "count" .
//pseudocode class foo static count = 0 def constructor() if count < 4 //create object else //there are too many!
, #
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(); } }