The Singleton Design Pattern makes sure that at any point of time, there is one and only one instance of a class present and also provides a global point of access to the object.
Examples:
Asser: Here is a simple Java example that illustrates the usage of Singleton with a class fields.
public class SingletonExample {
/** Singleton field that gets initialized only once if it exists **/
private String m_uniqueField;
/**
* Returns the content of the singleton field. The content
* gets initialized if it is empty.
*
* @return Millisecond time of the previous initialization (ALWAYS not null)
*/
public String getField() {
// Please notice that we are using the monitor of the instance
// itself, which means that all other methods gets synchronized
// as well.
synchronized (this) {
if (m_uniqueField == null) {
// Compute field
m_uniqueField = String.valueOf(System.currentTimeMillis());
}
return m_uniqueField;
}
}
/**
* Clear the content of the singleton field.
*/
public void clear() {
m_uniqueField = null;
}
}
question: How does this guarantee we're getting a unique response? Nothing prevents me from doing
a = new SingletonExample(); b = new SingletonExample();and getting different values from getField() (well, if we were looking at anything else than the current time...). Isn't a private constructor sort of a requirement of the singleton pattern, to guarantee one object instance?
(Delete this question if I'm off. -- ebu)
No, I think you're correct. You must have a private constructor, then use a static getInstance-method for getting a singleton "factory", if you will. --Janne
A few comments:
- It should be: public final class SingletonExample so I can't override its singleton behaviour adding another constructor.
- Use ThreadLocal if you need a Singleton per thread.
- Another way to achieve lazy initialization without synchronized:
public final class SingletonExample {
private static class LazySingletonHolder {
public static String m_uniqueField = String.valueOf(System.currentTimeMillis());
}
public static Singleton getField() {
return LazySingletonHolder.m_uniqueField;
}
...
}
--Jano