Difference between a static class and a singleton pattern – Interview Question


This is one of the favorite questions asked by interviewers.

I thought of putting my opinions on this topic.

  1. Most important singletons can be handled polymorphically without forcing their users to assume that there is only one instance.
  2. Singletons can implement interfaces (or derive from useful base classes).
  3. Singleton class follow the object oriented principles but not static class.
  4. A singleton can be initialized lazily or asynchronously while a static class is generally initialized when it is first loaded, leading to potential class loader issues.

My rule for choosing between static and singleton:

If there are bunch of functions should be kept together, then static is the choice.
Anything else which needs single access to some resources, could be implemented singleton.

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