Singleton Vs. Static Class

Well I was asked this question once. “What is a singleton design pattern and why should I use it? Why not use a static class instead?”

And it was quite surprising how it went. I said that Singleton is used when you need to maintain state. Static classes are used when you want to club together a bunch of stateless methods that do something irrespective of which instance calls these methods. Math class is a good example.

So he asked me, can I not maintain state in a static class? So I said if you want to instantiate something in a static class how would imageyou do it? And surprisingly he told me that he would do it in a static constructor. I asked him, is it possible to instantiate anything in the static constructor or even declare an instance type in a static class? And he asked me is it not possible? I said it is not as far as I know and he asked me if I am sure.

Now the way the questions were asked about this subject, I was quite surprised. The interviewer looked quite convinced that instance types can be declared in a static class. I am surprised how he was allowed to take the interview in the first place. Or was he checking my confidence?

I wonder.

Published Thursday, July 30, 2009 10:40 AM by Nilotpal Das

Comments

Thursday, August 06, 2009 4:48 AM by tintin

# re: Singleton Vs. Static Class

Why should state imply instance member? why not static member? And yes.. you can instantiate static members in static constructor. Encapsulation comes to mind, but the question, as you suggest is flawed, since it is like comparing design patterns to implementations - apples and oranges.

Thursday, August 06, 2009 2:48 PM by Nilotpal Das

# re: Singleton Vs. Static Class

state doesn't always imply instance member, but it may, considering your class candidate for singleton, has a complex type property. e.g. User type is a singleton candidate, which has a property addresses. a user may have more than one addresses. In this case, would it be prudent to make the User class static..?

I disagree on the apples and oranges thing. The intent is to maintain one state. now there are 2 implementations of this intent. one is a singleton and the other is a static class. We are comparing these implementations and whether static class cna replace singleton pattern or not.

Leave a Comment

(required) 
(required) 
(optional)
(required)