| Author |
Creating SingleTON without static variables
|
Rahul Krishnan
Greenhorn
Joined: Dec 06, 2011
Posts: 1
|
|
|
Can we create SingleTon classes without static variables.
|
 |
Hebert Coelho
Ranch Hand
Joined: Jul 14, 2010
Posts: 754
|
|
|
Yes, you can have instance variables and only an instance as static.
|
[uaiHebert.com] [Full WebApplication JSF EJB JPA JAAS with source code to download] One Table Per SubClass [Web/JSF]
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19232
|
|
|
But you will still need one static variable, to store the singleton instance itself.
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
Hebert Coelho
Ranch Hand
Joined: Jul 14, 2010
Posts: 754
|
|
Yes, but without it how would you controll the state of you class?
Unless you have a getInstance returning a new instance every time.
He asks:
Can we create SingleTon classes without static variables.
I reduced to one static, no more. [=
|
 |
Joanne Neal
Rancher
Joined: Aug 05, 2005
Posts: 3011
|
|
|
Use an Enum
|
Joanne
|
 |
John Jai
Bartender
Joined: May 31, 2011
Posts: 1778
|
|
Please check if this enum is a valid singleton ...
|
 |
Joanne Neal
Rancher
Joined: Aug 05, 2005
Posts: 3011
|
|
|
You don't need the constructor.
|
 |
John Jai
Bartender
Joined: May 31, 2011
Posts: 1778
|
|
|
Thanks! that makes all enums a singleton by itself?
|
 |
Joanne Neal
Rancher
Joined: Aug 05, 2005
Posts: 3011
|
|
John Jai wrote:Thanks! that makes all enums a singleton by itself?
It's probably a question of semantics.
There will only ever be one instance each of SingletonEnum.INSTANCE1, SingletonEnum.INSTANCE2 and SingletonEnum.INSTANCE3, but I guess you could argue that there are 3 instances of SingletonEnum.
|
 |
Stephan van Hulst
Bartender
Joined: Sep 20, 2010
Posts: 3065
|
|
Regardless, it's a form in instance control. I was thinking Joanne's point is that you can easily make a singleton like this:
|
 |
Joanne Neal
Rancher
Joined: Aug 05, 2005
Posts: 3011
|
|
Stephan van Hulst wrote:I was thinking Joanne's point is that you can easily make a singleton like this:
You think correctly.
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32833
|
|
. . . and welcome to the Ranch
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19232
|
|
|
Technically, enum constants are static final variables of the enum class. Just decompile such an enum with JAD or similar decompilers.
|
 |
 |
|
|
subject: Creating SingleTON without static variables
|
|
|