1. The intent of the Singleton is to ensure that a class has only one instance and to provide a global point of access to it.
2. A singleton is usually lazy-initialized. [lazy-initialized is like:if( filed == null) { // initial } return field; ]
3. Symchronize is important in lazy-initialize when initial Singleton (multi-thread).( see book: Concurrent Programming in Java )
4. See the source code of java.util.Collections.SingletonSet
5. UML diagram of Singleton, see pic:
6. To use Singleton, approaches are below:
6.1 use static function to create instance(and make the constractor private so that other can not use it),like:
public class Singleton {
private static Singleton s;
private Singleton(){};
// lazy-initialize
public static Singleton getInstance() {
if (s == null)
s = new Singleton();
return s;
}
}
6.2 Use static field to mark whether the single instance has been created, like:
class Singleton {
static boolean instance_flag = false; // true if 1 instance
public Singleton() {
if (instance_flag)
throw new SingletonException("Only one instance allowed"); //custom exception
else
instance_flag = true; // set flag for 1 instance
}
}
6.3 use Collection: repeat object is not allowed in some collections, can be extended to a specified number of instance of a class.