Friday, April 11, 2008

Limit Instances

Implement a class that limits the number of instances of itself to 4.


The answer will depend on the programming language. In fact, this might be technically impossible in some languages. However, in C++, Java, C#, and most others the basic idea is to use a static (class) variable to keep track of the number of instances and then write a constructor that refuses to work.



public class stooge{

public static int num = 0;

public void stooge( )
{
if (num < 4)
{
super( );
num++;
}
else {
throw new Exception("ERROR: too many instances");
}
}

}

No comments:

ShareThis