Forums Register Login

Difference between singleton and static class ?

+Pie Number of slices to send: Send


Please tell me what are the difference and when i need to go for singleton and static class ?
2
+Pie Number of slices to send: Send
They are not even close to the same thing.

A singleton is when you only want to allow and object to be instantiated ONCE. If you need some kind of gatekeeper that everyone talks to, so that all decisions are made by one person. Note: This is probably the most over-used (and possibly mis-used) design pattern.

A static class is used when you don't need ANY objects to be created. The Math class is a classic example. I don't need an actual Math object, I just need to be able to call the methods. There is no state that needs to be saved, so no object is needed.
+Pie Number of slices to send: Send
Is that a static class? I would have called it a utility class.
So what is a static class (apart from a kind of nested class)?
+Pie Number of slices to send: Send
Sorry ... I mean

Class X {


public static X getInstance() {

returns X;

}



+Pie Number of slices to send: Send
That looks like part of how you would implement a singleton in Java.

What do you mean by a "static class"? You cannot make a top-level class static. You can make nested classes static, which means that instances of the nested class don't have a reference to the object of the enclosing class. That, however, doesn't have anything to do with singletons.
+Pie Number of slices to send: Send
 

Campbell Ritchie wrote:Is that a static class? I would have called it a utility class.
So what is a static class (apart from a kind of nested class)?


Sorry...I was thinking of the Math class, where all the methods are static. I assumed that's what the OP meant, but I now realize I am probably wrong.
Put a gun against his head, pulled my trigger, now he's dead, that tiny ad sure bled
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 1090 times.
Similar Threads
Singleton Object
Synchronization
singleton vs static
difference between the singleton pattern class and static class
2 different types of singleton
More...

All times above are in ranch (not your local) time.
The current ranch time is
Apr 16, 2024 03:47:18.