views:

339

answers:

9

I've read the questions on S.O. regarding Singleton and just watched an hour long google tech talk. As far as I can tell, the consensus in the OO world seems to be that singletons are more of an anti-pattern rather than a useful design pattern.

That said, I am interviewing these days and the question comes up a lot--what is a singleton, and how would you use it?

What is the best way to answer this question? Should I simply describe the design pattern and then say the only acceptable use I've heard of is for logging, and that it is often mis-used for global state?

A: 

My answer would be:

A Singleton is a design pattern that specifies a method for ensuring that only 1 instance of an object exists at runtime.

I would use it with discretion.

Jordan S. Jones
You'd be wrong. A singleton is a design pattern that does what you say *AND* provides global access to the object. The second half of it is important too.
jalf
There is no requirement isn the singleton pattern that the singleton be global.
anon
Isn't there? Last I checked, the singleton pattern as described in the GoF book uses a public static method to gain access to the object - which means global access. That is what I understand by the term "singleton". If you don't provide global access then 1) I agree it becomes useful, and 2) I would no longer call it a singleton, at least not in the GoF sense
jalf
see my edited answer - the GoF book is not holy writ
anon
The global thing seems more like a common side-effect (of using public classes in the implementation) than a necessity... No reason you can't have restricted access to a singleton.
Shog9
@Neil: But the singleton name is derived from the pattern they defined. I agree that one or the other of the two traits provided by this pattern can be useful in isolation, but most people associate the word "singleton" with the GoF implementation, which provides *both* traits, a combination that is virtually always a bad idea. I think it just adds confusion to use the name "singleton" to describe objects that only offer one of these two traits
jalf
Sorry, The GoF people didn't invent the patterns they catalogue - all of them were very well known long before the book came out. I was certainly talking about singletons and using them in my code long before the book was published.
anon
Not sure if it makes a difference, but a singleton could also be internal (at least in c#).
SnOrfus
+4  A: 

Go with your own experience of using/not using it. That's the best answer any day. If you haven't used it, but do know what it is, go ahead and say so. Most of the time, it's the interviewer who'd not venture beyond Singletons -- so take a crack at it.

dirkgently
Having read the other answers, I'd like to add that interview answers should not be judgemental/give away a hint of personal bias. Which is bad, and which piques your interviewer (whichever camp he may be in). But then, that's just my viewpoint.
dirkgently
@dirkgently: Though maybe sound advice, I've had the opposite experience. As long as you're knowledgeable, and your argument is sound, a good discussion (as opposed to an argument) can really win points in an interview.
SnOrfus
Arguments are based on facts. Facts are undeniable. When I said judgemental -- I meant a statement not backed up by cold logic.
dirkgently
+2  A: 

So long as youy are prepared for a discussion, I think your suggested answer is a good one. But be aware that some of us still find singletons to be a useful idea. Some data is naturally global in scope, and singletons provide a sensible means of abstracting that data. You can of course also use singletons at more limiited scopes, for example within a specific namespace, if your language(s) support such a construct.

anon
++decent answer.
Shog9
I disagree. If you want global scope, you make the data global (or static, whatever your language allows). But the need for global data does not automatically imply that only one instance must exist, so a singleton is typically not the right answer.
jalf
+1  A: 

My answer:

Oh come on, couldn't you atleast find the second most popular question about this tired old subject? You had to go for the first? I'm leaving. the interview is over.

Or so I wish it could be...

shoosh
if the job market was better that might be a great answer!
alchemical
+4  A: 

Tricky. There are plenty of people who feel that singletons are essentially an anti-pattern like you said (me included), but there are also a lot who feel that it is simply an OOP-acceptable way to do globals.

If the interviewer is in that camp then yes, I think he's wrong, but that might not be the best thing to say during the interview. ;)

So I'd probably try to be neutral and stick to the facts. You don't know which camp your interviewer falls in, so stick to the indisputable facts. What does a singleton do? And to demonstrate usage, stick to the few cases where everyone can agree that a singleton is the correct answer. Or explain your experience (since people can't disagree with that either).

But whether you're "for" or "against" singletons, an interview is probably not the right time to crusade for that cause. ;)

jalf
+2  A: 

A singleton.

By definition it is an object that only has one instance throughout the entire application. This can be guaranteed by making the constructor private and providing a static instance via a public property in the object definition.

It is a useful pattern for when your handling a resource where only one object can access it any one time.

However it has many trade-offs. The singleton instance many have its own requirements making testing any class that uses it onerous as they have to fulfill its pre-requisites as well as the pre-requisites of the class being tested.

Furthermore it can be an issue when maintaining a project and attempting to modify some of the abstraction. Therefore I find it best to abstract a singleton via an interface. Keep the "single instance" as an implementation detail and pass the singleton instance around as the interface meaning that calling code isn't tied to the class definition (and static property). This makes it easier to test and abstract at a later date at the cost of architectural plumbing (e.g. passing it in to Ctors or setter properties).

Quibblesome
A: 

What about Singletons that have no state? I'm specifically thing of things like some possible idempotent Concrete Strategies in the Strategy Pattern, pure algorithm, no data.

Or Java Enum classes, which are Singletons. I find something like this useful:

public enum StringComparator implements Comparator {

  CASE_SENSITIVE {
    int compare(Object lhs, Object rhs) {
      // check for null omitted for brevity
      return lhs.equals(rhs);
    }
  },

  CASE_INSENSITIVE {
    int compare(Object lhs, Object rhs) {
      return String.CASE_INSENSITIVE_ORDER( lhs, rhs ) ;
    }
  };

  boolean equals( Object o ) {
   return this == o ;
  }
}
tpdi
With no state, it doesn't really matter whether there's one instance or one million instances, unless the instance *itself* is the state. Java has a lot of stuff like this simply because it doesn't allow function definitions outside of classes... After all, a class itself is a singleton.
Shog9
Except that one instance would take up a word of memory, and a million would take up a million words of memory.
tpdi
Again, unless you're using the instances themselves as state, this is just an irrelevant implementation detail.
Shog9
Also, if the class maintains no state, then it'd be even more prudent to make all of the methods static - and you'd not need to instantiate it at all.
SnOrfus
Well, Strategy Pattern relies on overriden virtual methods, so static won't work for that.
tpdi
+2  A: 

Likewise reminding everyone that the world did exist before the GoF, I'll add that one can also use modifications of the Singleton pattern to ensure only one instance per Session, or per Thread, or per whatever. Simply use per-Session or per-Thread or per-whatever state to hold the one-per instance.

John Saunders
A: 

There are a few uses I have run into. Logging is obvious. Another is console output using nCurses. I made a library that uses Panel objects, but each needed to communicate with a single Controller which controlled things like z-orders and such. One other is a random number generator for a game. Do you really want to reseed that mersenne twister in every function, or pass it around everywhere?

But for the most parts, they cause bad design.

rlbond