views:

278

answers:

8

Using a Singleton class guarantees one instance of a class to give control to the programmer. Really useful.

I was wondering if for example a Singleton Interface existed in a given framework to bypass the need to create/add one explicitly?

Would be handy to decalre:

public sealed class MySingleton : ISingleton  //or a different class 
    { ... }

And then expect the class to only ever be instantiated once.

Is this a good idea, or am I thinking a bit off the mark? :)

+2  A: 

Singleton does not prevent stack overflow, not sure what you are getting at with that.

For Java, what came to mind is Spring. By default, every Spring bean you write is a singleton. You can use it in 100 places, and they will all be set automagically via injection, and all 100 references will go to the same object (i.e. a singleton). When you set up a project in Spring, you can make any class you want a singleton just by following the conventions.

bwawok
all I meant was that if an application managed to instantiate a class too many times, eventually the stack would run out of reference space. right?
AlexW
Thats pretty interesting about Spring. I will be certain to investigate. Interested to see if there's a .NET equivalent.
AlexW
@AlexW - wrong. The only way that instantiating an object would cause a stack overflow would be if the constructor **recursively** instantiated instances of the same class. This is unrelated to the singleton pattern,
Stephen C
Strictly speaking Spring beans are not singleton. Rather, they are one instance per Spring context. However, you would only notice the distinction if 1) a webapp is restarted, or 2) if the same class is used by multiple webapps; i.e. via a common classloader. (The latter takes some work since webapps normally use different classloaders. So "the same" class is normally different ... across webapps in the web container.)
Stephen C
@Stephen C - the Singleton is used to guarantee one instance of a class in order to better manage memory consumption. I use a singleton to increase efficiency. Yes it's unlikely to cause a stack overflow at any point, but it could happen.
AlexW
I've updated the post accordingly ;)
AlexW
Using a singleton to manage memory is a bit off - this isn't the real purpose. The true purpose is to prevent multiple instances from existing, to share resources, common data, etc. In truth it's a bit of an anti-pattern and tends to lead to code that is difficult to test. Better off not coupling the behavior of a class with the logic of how it is instantiated.
matt b
That makes a lot of sense @matt b
AlexW
@AlexW - *"Yes it's unlikely to cause a stack overflow at any point, but it could happen."* That is incorrect. You can create an arbitrarily large number of instances of a class without EVER getting a stack overflow. Yes, you might fill up the heap ... but a stack overflow is virtually impossible unless there is recursion involved.
Stephen C
@Stephen C - Ok but it could be possible to force a recursive instantiation and break the program...
AlexW
@AlexW - the only way to "force" recursive instantiation is if your constructor is coded to do that. I cannot conceive of a real use-case where you'd want a constructor to recurse; it's just bizarre, IMO. And anyway, invoking a recursive constructor **just once** risks causing the stack to blow up. Singletons simply don't help with this.
Stephen C
@Stephen C - I was thinking more along the lines of security and code patching to break programs using recursion. It might be possible, who knows? :)
AlexW
The point is that 1) you have to do bizarre and perverse things to cause a stack overflow in a constructor, and 2) the use of a singleton won't protect you.
Stephen C
@Stephen C - yep I suppose you're right there +1
AlexW
@Stephen C - although, Singletons are borne out of a time when memory consumption was very pressured. So using the resources through complex objects was limited. Singletons are very useful.
AlexW
In some situations they can be convenient, in others they can be harmful; see @BalusC's answer. In my experience, the harm outweighs the convenience in most applications.
Stephen C
Is this because of code re-usability? Singletons could be coupled to their implementation in the calling object. This could cause problems in future projects. Having said that, why not create discreet Singleton classes. It seems safer in it's locking procedure than Static.
AlexW
Also, although my knowledge is limited... Singletons are instances and offer the benefits of dynamic interaction at runtime.
AlexW
+7  A: 

I was wondering if for example a Singleton Interface existed in a given framework to bypass the need to create/add one explicitly?

It doesn't and can't exist. A singleton basically requires a static Singleton getInstance() method, but because it's static, it cannot be definied as an abstract (interface) method. It also makes sense, there can be only one singleton implementation, not multiple. Abstracting it is pointless.

You'll need to boilerplate complete singletons yourself. I however highly question how that's useful. It's certainly not its sole purpose to prevent stackoverflow or memory errors. Writing good code prevents that. Singletons are only useful if you want to have the enduser to deal with the same instance all the time. Which can be done as good without the singleton pattern by the way. Either just declare it static or make use of the "application scope" concept the average framework can provide you.

Instead of singletons, rather look for inversion of control (dependeny injection). That's by the way also exactly what Spring is doing. They do not use "pure" singletons. It was a poor word choice they made.

See also:

BalusC
Am I right in thinking Microsoft thinks Singletons are evil? They won't implement even a 'virtual singleton' that exists in Java right now. I'm not sure I can see the problem with the judicious use of them.
AlexW
Also, although my knowledge is limited... Singletons are instances and offer the benefits of object inheritance at runtime. Is this not true?
AlexW
Singletons are evil in OOP. Inheritance is pointless in a singleton since it's static and final. You can't extend from it nor abstract it. You can't replace or mock it. No polymorphism as well. That it in turn inherits from Object has basically the only advantage that you can instantiate it.
BalusC
A: 

The intention behind the singleton pattern is "Configure once. Use multiple times". This is typically used to share any kind of data or resources as mentioned in one of the answers above. But it is also useful to enable any kind of "management" application. (think JMX if it is Java)

You have one instance of a certain class that you can use multiple times. Since there is only one instance, by configuring that instance appropriately, you can reflect the configuration changes across the app. Hence the singleton pattern gives the ability to enable a "management dashboard" to your app.

Spring or Spring.NET (the .NET implementation of Spring) are useful for configuring and injecting singletons. The same arguments apply for any kind of dependency injection framework. You should read about dependency injection in general to harness the full power. A true singleton, across multiple JVMs or clusters, is usually harder to create and manage. and might require tool support. In practice, it is not necessary to create and maintain that.

Don't confuse singletons with statics! The construct looks similar but it can be pretty different. Now to drum my own trumpet! Here is a link to an article that I had written about static methods.

raja kolluru
Your article makes for a good case against the use of static. It seems to be used as a 'fix' and then regretted upon later. +1
AlexW
"Don't confuse singletons with statics!" Boggle.
Tom Hawtin - tackline
Is not confusion, it's forgetting about what works in my particular project.
AlexW
+2  A: 

Google Guice is a dependency-injection framework that supports a @Singleton annotation.

Note that classes annotated with @Singleton aren't "true" singletons - there's nothing stopping client code from creating many instances of such a class. However, Guice-managed dependencies will all share the same instance.

See http://code.google.com/p/google-guice/wiki/Scopes

harto
Why are 'manual singletons error prone' from a comment on the Guice link? "If you now wanted to have one type instance per JVM, I suggest that you roll your own Scope implementation. Try to stay away from manual singletons: they are error prone and make testing your code harder. so guice doesnt support real singletons"
AlexW
For the reasons discussed in the articles that BalusC linked to.
harto
+1  A: 

Maybe not what you're looking for, but here's my favorite version of the singleton pattern in C#. It's thread-safe, uses lazy instantiation, and doesn't require any locks. It's also pretty painless to write... no frameworks needed. ;)

class MyClass
{
  // ...
  #region Singleton pattern
  private MyClass() { }
  public static MyClass Instance { get { return Singleton.instance; } }
  class Singleton
  {
    static Singleton() { }
    internal static readonly MyClass instance = new MyClass();
  }
  #endregion
  // ...
}

To get the object instance:

MyClass m = MyClass.Instance;
no
+1 nice 1 dude. :)
AlexW
+1  A: 

In Java you can do this simply with an enumerated type. You specify the number of instances so that there can be none (also called a utility class), one (also called a singleton) or more as you choose.

public enum MySingleton {
    INSTANCE;
} 
Peter Lawrey
What does INSTANCE represent exactly? The reference to the object? This enum is nested in an instance class/object or a static class?
AlexW
The INSTANCE is the only enum values/object. It is basically the same as defining a public static final MySingleton INSTANCE = new MySingleton(); with a private constructor. The enum can be nested or not as you choose.
Peter Lawrey
+1  A: 

.NET 4.0 has the Lazy(T) Class, which will lazily-initialize a value on first access, in a thread-safe manner. There are lots of examples at the Lazy Initialization topic.

Also, if you are using Unity, there is a lifetime manager which you can configure with the ContainerControlledLifetimeManager to ensure a single instance.

Olivier Dagenais
+1  A: 

Ruby has a module called singleton that makes the class which includes it a singleton. This module is built into the standard library.

tgandrews