I understand that a singleton class is one where there can be only one instantiation, but I don't understand why this would be useful. Why won't you just create a class with static variables and methods and use synchronize if needed to make sure that no two threads were executing a method in the class simultaneously. I just don't get why anyone would go through the trouble of creating this kind of class. I know I'm missing something here.
Thanks,
It is used where only a single instance of a class is required to control the action throughout the execution. A singleton class shouldn't have multiple instances in any case and at any cost. Singleton classes are used for logging, driver objects, caching and thread pool, database connections.
Singleton is like a single resource which is being shared among multiple users; for example - sharing a single washing machine among all the residents in a hotel or sharing a single appliance like refrigerator among all the family members.
A Singleton can implement interfaces, inherit from other classes and allow inheritance. While a static class cannot inherit their instance members. So Singleton is more flexible than static classes and can maintain state. A Singleton can be initialized lazily or asynchronously and loaded automatically by the .
While I agree with the other answers, the OP was asking why not have a class with all static methods (possibly with static fields) instead of a singleton where you have one instance.
Why use Singletons?
You can Google "singleton" to find all sorts of reasons. From JavaWorld:
Sometimes it's appropriate to have exactly one instance of a class: window managers, print spoolers, and filesystems are prototypical examples. Typically, those types of objects—known as singletons—are accessed by disparate objects throughout a software system, and therefore require a global point of access. Of course, just when you're certain you will never need more than one instance, it's a good bet you'll change your mind.
Why use a Singleton instead of a class with all static methods?
A few reasons
For #3, if your Singleton was a database connection pool, you want to insure that your application has only one instance, but do unit testing of the database connection pool itself without hitting the database (possibly by using a package-scope constructor or static creational method):
public class DatabaseConnectionPool { private static class SingletonHolder { public static DatabaseConnectionPool instance = new DatabaseConnectionPool( new MySqlStatementSupplier()); } private final Supplier<Statement> statementSupplier; private DatabaseConnectionPool(Supplier<Statement> statementSupplier) { this.statementSupplier = statementSupplier; } /* Visibile for testing */ static DatabaseConnectionPool createInstanceForTest(Supplier<Statement> s) { return new DatabaseConnectionPool(s); } public static DatabaseConnectionPool getInstance() { return SingletonHolder.instance; } // more code here }
(notice the use of the Initialization On Demand Holder pattern)
You can then do testing of the DatabaseConnectionPool
by using the package-scope createInstanceForTest
method.
Note, however, that having a static getInstance()
method can cause "static cling", where code that depends on your singleton cannot be unit tested. Static singletons are often not considered a good practice because of this (see this blog post)
Instead, you could use a dependency injection framework like Spring or Guice to insure that your class has only one instance in production, while still allowing code that uses the class to be testable. Since the methods in the Singleton aren't static, you could use a mocking framework like JMock to mock your singleton in tests.
A class with only static methods (and a private contructor) is a variant where there is no instance at all (0 instances).
A singleton is a class for which there is exactly 1 instance.
Those are different things and have different use cases. The most important thing is state. A singleton typically guards access to something of which there is logically only ever one. For instance, -the- screen in an application might be represented by a singleton. When the singleton is created, resources and connections to this one thing are initialized.
This is a big difference with a utility class with static methods - there is no state involved there. If there was, you would have to check (in a synchronized block) if the state was already created and then initialize it on demand (lazily). For some problems this is indeed a solution, but you pay for it in terms of overhead for each method call.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With