Factsheet
java - I dont understand the concept of a singleton class - Stack Overflow
design patterns - why are there java singleton classes? When would you need to use one - Stack Overflow
Singleton pattern in java..
java - What is a singleton, in plain English? - Stack Overflow
Can I use Enum for implementing Singleton?
How does serialization affect Singleton?
Can a Singleton class be subclassed?
Videos
Singletons are used for when you want exactly one instance of a class, that the entire application shares.
Good examples for this principle are classes that are in charge of accessing external resources. For example, you'd want the entire application share the same database connection (or at least connection pool), not have every class that needs it open its own connection.
In some cases, we need to expose a shared resource throughout the application e.g. DB connection but we don't want to
- create shared object up-front (before creation of client objects).
- explicitly pass shared object to each client object.
then we can use Singleton design pattern.
Typical Singleton class looks like
public class MySingleton {
private MySingleton INSTANCE
private MySingleton() {
}
public static MySingleton getInstance() {
if (INSTANCE == null) {
syncronized (MySingleton.class) {
if (INSTANCE == null) {
INSTANCE = new MySingleton();
}
}
}
return INSTANCE;
}
// instance methods exposing business operation
}
But we can achieve the similar behaviour by making each and every instance methods which are exposing business operation as static. In this approach we don't even need to create single object.
Then why do we need Singleton?
Well, the answer is simple. To isolate actual implementation from the client. Basically we are applying abstraction OOP principle here.
This is helpful If the singleton class is part of library which is used by various clients and library wants to vary the implementation as per the client.
Sample for such singleton can be
public class MySingleton {
private MySingleton INSTANCE
private MySingleton() {
}
public static MySingleton getInstance() {
if (INSTANCE == null) {
syncronized (MySingleton.class) {
if (INSTANCE == null) {
INSTANCE = new MySingletonChild(); // here we are creating an object of subclass of MySingleton.
}
}
}
return INSTANCE;
}
// instance methods exposing business operation
}
Hope this help in understanding Singleton design pattern.
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
- You could use inheritance
- You can use interfaces
- It makes it easier to do unit testing of the singleton class itself
- It makes it possible to do unit testing of code that depends on the singleton
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.
What is singleton pattern in java..? what advantage of use this.? why singleton pattern is used??. please explain me with real life example..
The simple plain English1 version is: Singleton Class is a Class that has, and can only have, only one instance.
But can't you just then use a static class for that?
No. That's not what a "static" class is in Java. In Java "static" classes can have multiple instances just like any other class.
The static keyword is used (for classes) to mean that the instance of a nested class is not tied to a specific instance of the enclosing class. And that means that expressions in the nested class cannot refer to instance variables declared in the enclosing class.
Prior to Java 1.5 (aka Java 5), there was no support for the singleton design pattern in Java. You just implemented them in plain Java; e.g.
/** There is only one singer and he knows only one song */
public class Singer {
private static Singer theSinger = new Singer();
private String song = "I'm just a singer";
private Singer() {
/* to prevent instantiation */
}
public static Singer getSinger() {
return theSinger;
}
public String getSong() {
return song;
}
}
Java 1.5 introduced the enum types which can be used to implement singletons, etc.
/** There are two Singers ... no more and no less */
public enum Singer {
DUANE("This is my song"),
RUPERT("I am a singing bear");
private String song;
Singer(String song) {
this.song = song;
}
public String getSong() {
return song;
}
}
1 - Of course, you need to understand what "class" and "instance" mean. Since the Programming / IT English meanings of these words is different to the "plain English" meanings, it is a stretch to call this a "plain English" description. On the other hand, if the reader doesn't already understand what "class" and "instance" mean, they don't have the base knowledge needed to understand the "singleton" idea, or see the point of it.
singleton is a class with a private constructor and you could only get one instance of it. for further explanation why this coding style is done I suggest you read the chapter regarding singletons in this book
http://www.wowebook.com/book/head-first-design-patterns/
Chapter 5 is all about singleton