The singleton mode is a very basic design pattern, which may be asked to write different types of singleton code in the interview, there are three main modes:
1. A Hungry man mode:
A hungry man mode, very hungry very anxious, so the class is loaded when the instance object is created public
class Singleton1 {
private static Singleton1 singleton = new Singleton1 ();
Private Singleton1 () {
} public
static Singleton1 getinstance () {
return singleton;
}
}
2, full-han mode:
Full-han mode, very full not anxious, delay loading, when to use when to create an instance, there is a thread safety issue public
class Singleton2 {
private static Singleton2 singleton;
Private Singleton2 () {
} public
static synchronized Singleton2 getinstance () {
if (singleton = = null)
singleton = new Singleton2 ();
return singleton;
}
}
3. Double Lock mode:
Full-han mode double lock mode, improve efficiency public
class Singleton3 {
private static Singleton3 singleton;
Private Singleton3 () {
} public
static Singleton3 getinstance () {
if (singleton = = null) {
synchronized ( Singleton3.class) {
if (singleton = = null) {
singleton = new Singleton3 ();}}
}
return singleton;
}
}
Comparison of several modes:
1. The A Hungry man mode is thread-safe because instance objects are created during class loading and simply return object references in the GetInstance () method. The reason is called "A Hungry Man", because this mode creates instance object compared "urgent", really is hungry ...
Benefits: Simple and straightforward, no need to focus on thread safety issues.
Cons: If you use too many a hungry man singleton in a large environment, you will produce too many instance objects, whether you want to use them or not.
2, the full-han mode is not thread-safe, because it is necessary to produce an instance object, before production will determine whether the object reference is empty, here, if multiple threads at the same time into the judgment, will generate multiple instance objects, which is not in line with the idea of a singleton. So the full-Han mode to ensure thread safety, the Synchronized keyword is used to identify the method. The reason is called "full-han", because it is full, not in a hurry to produce examples, when needed to produce.
Benefits: Delayed loading, when used to produce objects.
Cons: Need to ensure synchronization, pay the cost of efficiency.
3, double lock mode , is the optimization of the full-Han mode, double judgment, when the instance object has been created without locking, improve efficiency. is also a recommended way to use.