How you can limit a class to create only two instances ?

How you can limit a class to create only two(n) instances ?

This is one of my favorite question in an interview.So before watching the answer take a minute and think how you can create a such class .. tough ? Ahan its very easy.

 Answer : The basic idea is create a static property and increment that in constructor every time you are creating an object of that class. And throw an exception when that count is greater than two.

next question which can be ask is :

How you will decrement the count of that property when object is disposed ? Is it thread safe ?

Answer : you will use destructor for that and decrement the count there. Additionally to make it thread safe we can use LOCK keyword or INTERLOCKED keyword.

Below is the running example :

http://ift.tt/2jKlXow

Hope my this series will help somebody to get a job πŸ™‚ πŸ™‚ . Happy coding πŸ™‚ 

via Blogger http://ift.tt/2jJfEBc January 21, 2017 at 12:04PM

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s