最基本的實現方式如下: 代碼如下:
package singletonpattern;
public class Singleton1 {
private static Singleton1 uniqueInstance;
private Singleton1() {
}
public static Singleton1 getInstance() {
if (uniqueInstance == null) {
uniqueInstance = new Singleton1();
}
return uniqueInstance;
}
}
但是以上方法並沒有考慮到多線程的情況,如果是多線程,仍有可能創建多個實例,因此可以通過加鎖和同步來實現多線程的單件模式,同步的缺點是效率大大降低:
代碼如下:
package singletonpattern;
public class Singleton2 {
private static Singleton2 uniqueInstance;
private Singleton2() {
}
public static synchronized Singleton2 getInstance() {
if (uniqueInstance == null) {
uniqueInstance = new Singleton2();
}
return uniqueInstance;
}
}
還有一種方法是自動初始化,這樣肯定不會造成多個實例,但是如果實際沒有用到的話也會初始化實例,浪費了資源:
代碼如下:
package singletonpattern;
public class Singleton3 {
private static Singleton3 uniqueInstance = new Singleton3();
private Singleton3() {
}
public static Singleton3 getInstance() {
return uniqueInstance;
}
}
使用內部類的方法可以解決過早初始化的問題:
代碼如下:
public class Singleton5 {
private Singleton5(){
}
public static Singleton5 getInstance(){
return Nested.instance;
}
static class Nested{
static Singleton5 instance = new Singleton5();
}
}
用於多線程的改進方法如下:
代碼如下:
package singletonpattern;
public class Singleton4 {
private volatile static Singleton4 uniqueInstance;
private Singleton4() {
}
public static Singleton4 getInstance() {
if (uniqueInstance == null) {
synchronized (Singleton4.class) {
if (uniqueInstance == null) {
uniqueInstance = new Singleton4();
}
}
}
return uniqueInstance;
}
}
使用了雙重保險,雙重檢查,當沒有實例化的時候才進行加鎖和同步。