五種單件形式之Singleton的完成辦法詳解。本站提示廣大學習愛好者:(五種單件形式之Singleton的完成辦法詳解)文章只能為提供參考,不一定能成為您想要的結果。以下是五種單件形式之Singleton的完成辦法詳解正文
最根本的完成方法以下:
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;
}
}
應用了兩重保險,兩重檢討,當沒有實例化的時刻才停止加鎖和同步。