Question

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?

Was it helpful?

Solution

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 most people can agree that a singleton is an acceptable 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. ;)

OTHER TIPS

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.

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.

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).

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.

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...

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.

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 ;
  }
} 

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top