I need to create a singleton class without keeping a static method.
How can i do that?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Create an enum with one instance
EDIT: The Java Enum Tutorial shows you how to add fields and methods to an enum.
BTW: Often when you can use a Singleton, you don’t really need one as utility class will do the same thing. The even shorter version is just
Where Singletons are useful is when they implement an interface. This is especially useful for testing when you using Dependency injection. (One of the weakness of using a Singleton or utility class substitution in unit tests)
e.g.
As you can see, if your code uses TimeService everywhere, you can inject either the
VanillaTimeService.INSTANCEor anew FixedTimeService()where you can control the time externally i.e. your time stamps will be the same every time you run the test.In short, if you don’t need your singleton to implement an interface, all you might need is a utility class.