Singleton pattern vs Static classes
Monday, September 17, 2007 9:13:19 AM
If you want a simple class that's accessible from everywhere in your code, you could easily use a static class to achieve this.
In PHP, you can use :: to access classes statically: MyClass::doSomething(), in C# you can declare a class static and so on. It's much simpler to create and access static classes than singleton classes, too.
The singleton does have some advantages though...
With Singleton, you can keep track of who's using it easily. This is because you need to call the getInstance() or whatever method which returns an instance of the class.
Also, because of the above, you can control the amount of actual instances. In some special cases, it might be useful to have multiple instances of the singleton class, for example for load balancing.
You can also give a singleton some parameters. When working with static classes, you may need to pass a lot of parameters to the methods of the class because you aren't "constructing" it. This can, however, be avoided by using a method in the static class that saves the parameters and calling the method you want after that which is pretty much equal to first calling the singleton's getInstance with your parameters and then calling its method.
Singleton also gives a reference/pointer to the class instance. You can then pass this reference as a parameter for some other function for example. If you were using static classes, the other function would have to use the class statically too and if you ever needed to change the behavior, you would need to rewrite parts of that function too instead of just having the first one pass a different class as the parameter.
There's also an another side to the reference thing. If you use the reference in your class and decide that you won't need a singleton anymore, but a normal class, you will just need to change the behavior of the class itself and perhaps replace the line which gets an instance of it to constructing a new one or such. If you were using a static class, you would have to rewrite a lot of the code to use the new reference to the class instead of the static class name. A singleton class should also work almost out of the box as a normal class too. If you had a static class and wanted to convert it to a normal one, you would have to rewrite many parts of it.
You can't extend static classes, but singletons you can. Except it doesn't work very well in PHP due to some issues with static method inheritance, but it's not the only language in the world and it can be done but slightly hackily.
So if we think about it with all this, why would you use static classes at all?
They have their uses too - For example for library code they can be nice, such as the static System.Math class in C#.