views:

416

answers:

11

How is a singleton different from a class filled with only static fields?

+1  A: 

At least you can more easily replace it by a mock or a stub for unit testing. But I am not a big fan of singletons for exactly the reason you are describing : it are global variables in disguise.

Peter Tillemans
Actually, I think having a singleton helps you reduce the number of global variables. You have one reference to an object. It could wrap all the static fields into it.
BenoitParis
@BenoitParis - it reduces the absolute number of global variables but does not solve any of the evils associated with them.
D.Shawley
You shouldn't have global variables in the first place. Even having static methods is not really OOP.
Raoul Duke
@BenoitParis Anything you can access through a Singleton is a global variable just as much as any other... it's just accessed as Singleton.getInstance().whatever() instead of another way.
ColinD
@D.Shawley - My bad. Can you elaborate a bit?
BenoitParis
@D.Shawley Quite. Singletons just add more complexity whilst addressing none of the problems caused.
Tom Hawtin - tackline
The cleanest way to make something a singleton (assuming server side programming) is to declare a named bean via a Spring application context. If you set scope="singleton" then calling appContext.getBean() repeatedly returns the same instance. If you set scope="prototype" then every invocation returns a new instance. Means the code doesn't have to implement or worry getInstance(), you just get the bean.Singleton is the default since most beans are singletons anyway.<bean id="myBean" class="com.foo.myBean" scope="singleton"/>
locka
@locka Any kind of dependency injection container with a singleton scope, not just Spring.
ColinD
@locka Absolutely! Using dependency injection to inject singletons is the way to go provided it are either infrastructure services like database connectors,caches,... or 'stateless' service beans in the meaning that they do not have externally visible internal state. Then the other code will not make dangerous assumptions and life is a lot simpler.
Peter Tillemans
+4  A: 

A singleton can be initialized lazily, for one.

JRL
Statics are anyway.
Tom Hawtin - tackline
@Tom Hawtin - tackline: what do you mean by that?
JRL
Statics fields aren't really lazy loaded. Static fields are loaded when the class is loaded by a class loader. A singleton may be written such that the singleton instance is not initialized on class loading, but instead on the first request for the singleton instance. Of course, the most common approach for singletons is not lazy.
Brian M. Carr
+2  A: 

A singleton is a class with just one instance, enforced. That class may have state (yes I know static variables hold state), not all of the member variables or methods need be static.

A variation would be a small pool of these objects, which would be impossible if all of the methods were static.

uncle brad
Question asks about fields, not methods.
Tom Hawtin - tackline
+3  A: 

The difference is language independent. Singleton is by definition: "Ensure a class has only one instance and provide a global point of access to it. " a class filled with only static fields is not same as singleton but perhaps in your usage scenario they provide the same functionality. But as JRL said lazy initiation is one difference.

Numenor
+1  A: 

A singleton class will have an instance which generally is one and only one per classloader. So it can have regular methods(non static) ones and they can be invoked on that particular instance.

While a Class with only static methods, there is really no need in creating an instance(for this reason most of the people/frameworks make these kind of Util classes abstract). You will just invoke the methods on class directly.

Teja Kantamneni
+1  A: 

The first thing that comes to mind is that if you want to use a class with only static methods and attributes instead of a singleton you will have to use the static initializer to properly initialise certain attributes. Example:

class NoSingleton {
  static {
    //initialize foo with something complex that can't be done otherwise
  }
  static private foo;
}

This will then execute at class load time which is probably not what you want. You have more control over this whole shebang if you implement it as a singleton. However I think using singletons is not a good idea in any case.

Raoul Duke
I think for you to say that singletons are "not a good idea", when we don't know anything about the context that he might be using them, is a little rash. There are no absolutes in programming, and there is almost always a use case that makes one or the other the best. It's like telling someone the word "duck" always refers to an animal. But context is important, since it could mean something completely different like "Duck when someone throws a show at you." P.S. But I did not downvote you.
AaronLS
A: 

NOTE: The examples are in C#, as that is what I am more familiar with, but the concept should apply to Java just the same.

Ignoring the debate on when it is appropriate to use Singleton objects, one primary difference that I am aware of is that a Singleton object has an instance that you can pass around.

If you use a static class, you hard-wire yourself to a particular implementation, and there's no way to alter its behavior at run-time.

Poor design using static class:

public class MyClass
{
   public void SomeMethod(string filename)
   {
      if (File.Exists(filename))
        // do something
   }
}

Alternatively, you could have your constructor take in an instance of a particular interface instead. In production, you could use a Singleton implementation of that interface, but in unit tests, you can simply mock the interface and alter its behavior to satisfy your needs (making it thrown some obscure exception, for example).

public class MyClass
{
   private IFileSystem m_fileSystem;

   public MyClass(IFileSystem fileSystem)
   {
      m_fileSystem = fileSystem;
   }

   public void SomeMethod(string filename)
   {
      if (m_fileSystem.FileExists(filename))
         // do something
   }
}

This is not to say that static classes are ALWAYS bad, just not a great candidate for things like file systems, database connections, and other lower layer dependencies.

ph0enix
A: 

One of the main advantages of singletons is that you can implement interfaces and inherit from other classes. Sometimes you have a group of singletons that all provide similar functionality that you want to implement a common interface but are responsible for a different resource.

doobop
+9  A: 

Almost every time I write a static class, I end up wishing I had implemented it as a non-static class. Consider:

  • A non-static class can be extended. Polymorphism can save a lot of repetition.
  • A non-static class can implement an interface, which can come in handy when you want to separate implementation from API.

Because of these two points, non-static classes make it possible to write more reliable unit tests for items that depend on them, among other things.

A singleton pattern is only a half-step away from static classes, however. You sort of get these benefits, but if you are accessing them directly within other classes via `ClassName.Instance', you're creating an obstacle to accessing these benefits. Like ph0enix pointed out, you're much better off using a dependency injection pattern. That way, a DI framework can be told that a particular class is (or is not) a singleton. You get all the benefits of mocking, unit testing, polymorphism, and a lot more flexibility.

StriplingWarrior
A: 

Singleton Class : Singleton Class is class of which only single instance can exists per classloader.

Helper Class (Class with only static fields/methods) : No instance of this class exists. Only fields and methods can be directly accessed as constants or helper methods.

These few lines from this blog describes it nicely:

Firstly the Singleton pattern is very useful if you want to create one instance of a class. For my helper class we don't really want to instantiate any copy's of the class. The reason why you shouldn't use a Singleton class is because for this helper class we don't use any variables. The singleton class would be useful if it contained a set of variables that we wanted only one set of and the methods used those variables but in our helper class we don't use any variables apart from the ones passed in (which we make final). For this reason I don't believe we want a singleton Instance because we do not want any variables and we don't want anyone instantianting this class. So if you don't want anyone instantiating the class, which is normally if you have some kind of helper/utils class then I use the what I call the static class, a class with a private constructor and only consists of Static methods without any any variables.

YoK
+2  A: 

Let's me sum up :)

The essential difference is: The existence form of a singleton is an object, static is not. This conduced the following things:

  • Singleton can be extended. Static not.
  • Singleton creation may not be threadsafe if it isn't implemented properly. Static not.
  • Singleton can be passed around as an object. Static not.
  • Singleton can be garbage collected. Static not.
  • Singleton is better than static class!
  • More here but I haven't realized yet :)

Last but not least, whenever you are going to implement a singleton, please consider to redesign your idea for not using this God object (believe me, you will tend to put all the "interesting" stuffs to this class) and use a normal class named "Context" or something like that instead.

instcode
+1 for the "God Object" principle. Love it.
StriplingWarrior