Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singleton classes

Is there any difference between a Singleton class and a class with all static members (i.e. methods and attributes).

I could not find any instance where 'all static member class' would not achieve the same functionality as class properly implementing Singleton pattern?

For eg. java.lang.Runtime is a proper Singleton class whereas java.lang.System has all static method for access and merely has a private constructor to avoid external construction . Does anybody know why classes like Runtime are made Singleton and not implemented like java.lang.System.

Is it merely because it would be a cleaner design (i.e. mimics an object more realistically) or is there some performance benefit here?

like image 585
Flash Avatar asked Dec 15 '10 08:12

Flash


People also ask

What is the use of singleton classes?

Singleton classes are used for logging, driver objects, caching and thread pool, database connections. An implementation of singleton class should have following properties: It should have only one instance : This is done by providing an instance of the class from within the class.

What is an example of a singleton?

Example. The Singleton pattern ensures that a class has only one instance and provides a global point of access to that instance. It is named after the singleton set, which is defined to be a set containing one element. The office of the President of the United States is a Singleton.

How can we create a singleton class?

To create the singleton class, we need to have static member of class, private constructor and static factory method. Static member: It gets memory only once because of static, itcontains the instance of the Singleton class. Private constructor: It will prevent to instantiate the Singleton class from outside the class.

Why do we need singleton class?

Singleton pattern restricts the instantiation of a class and ensures that only one instance of the class exists in the Java Virtual Machine. The singleton class must provide a global access point to get the instance of the class. Singleton pattern is used for logging, drivers objects, caching, and thread pool.


2 Answers

Yes, there's a difference - a singleton can implement an interface.

Also, what looks like a singleton from the outside can actually be implemented via different classes, where the singleton access method (e.g. Runtime.getRuntime()) can create the right instance at execution time. I'm not saying that's what's happened here, but it's an option.

like image 103
Jon Skeet Avatar answered Sep 24 '22 12:09

Jon Skeet


Well you can serialize and unserialize an object (and thus a Singleton) using the Serializable interface (on Java), but not a static class.

like image 20
mauris Avatar answered Sep 24 '22 12:09

mauris