Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Singleton vs Static Class [duplicate]

Possible Duplicate:
Difference between static class and singleton pattern?

Just wanted to know what exactly is the difference between a singleton and static class?

like image 550
Sarfraz Avatar asked May 25 '10 12:05

Sarfraz


People also ask

Why should you avoid singletons?

The most important drawback of the singleton pattern is sacrificing transparency for convenience. Consider the earlier example. Over time, you lose track of the objects that access the user object and, more importantly, the objects that modify its properties.

Which is better Singleton or static class?

A Singleton class can Dispose, while a static class can not. A Singleton class can have a constructor, while a static class can only have a private static parameterless constructor and cannot have instance constructors. A Static class has better performance since static methods are bonded on compile time.

What if I use static instead making Singleton?

It is not possible to inherit from a static class, while it is possible with singleton pattern if you want to allow it. So, anyone can inherit from a singleton class, override a method and replace the service. It is not possible to write an extension method to a static class while it is possible for a singleton object.

Why is Singleton better than static?

The singleton, like any other instance of a class, lives on the heap. To its advantage, a huge singleton object can be lazily loaded whenever required by the application. On the other hand, a static class encompasses static methods and statically bound variables at compile time and is allocated on the stack.


1 Answers

In a singleton you can choose to initialize the variable at first call. Whereas a static variable starts to exists at the moment you include / call the file where the static variable is declared.

like image 168
Snake Avatar answered Sep 30 '22 19:09

Snake