| Author |
Difference between singleton and static class ?
|
Praveen Kumar
Ranch Hand
Joined: Nov 06, 2006
Posts: 133
|
|
Please tell me what are the difference and when i need to go for singleton and static class ?
|
 |
fred rosenberger
lowercase baba
Bartender
Joined: Oct 02, 2003
Posts: 9939
|
|
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.
|
Never ascribe to malice that which can be adequately explained by stupidity.
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32611
|
|
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)?
|
 |
Praveen Kumar
Ranch Hand
Joined: Nov 06, 2006
Posts: 133
|
|
Sorry ... I mean
Class X {
public static X getInstance() {
returns X;
}
|
 |
Jesper de Jong
Java Cowboy
Bartender
Joined: Aug 16, 2005
Posts: 12907
|
|
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.
|
Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
|
 |
fred rosenberger
lowercase baba
Bartender
Joined: Oct 02, 2003
Posts: 9939
|
|
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.
|
 |
 |
|
|
subject: Difference between singleton and static class ?
|
|
|