lundi 9 mars 2015

How can we make sure that we can just create one instance of a class?

This was an interview question. The interviewer presented me a class Person and another Class Community. He wanted to know what can we do to make sure that within the Class Community, the instance of the Class Person can be called once.


My approach was to define a boolean flag as a Global variable and to check in the constructor of Class Person if the flag value was false, then it will create the instance or else return error. This flag value is changed to true with the creation of the first instance of Class Person.He did not seem very satisfied with the answer.


I understand that this may be not the right way of doing this. Question is, is there a way to do so using Class definition,or a specific type of class?


Aucun commentaire:

Enregistrer un commentaire