[英]Differences between two singleton examples
A級1級
public class A {
private static final A instance = new A();
public static A getInstance() {
return new A();
}
}
A 2級
public class A {
private static final A instance = new A();
private A(){}
public static A getInstance() {
return instance;
}
}
我剛剛開始學習單例,並且看到了兩個Java示例,分別使用A 1類示例和A 2類示例。 A 1類getInstance()
是單例嗎? 我還想知道這兩個A類getInstance()
方法之間的區別是什么? 謝謝
我也想知道這兩個A類getInstance()方法之間的區別
A類1:
如果您看一下代碼:
public static A getInstance() {
return new A();
}
您在每次調用getInstance()
方法時都返回一個新的A
實例,因此它不是Singleton。 同樣,在這種情況下,您沒有將默認構造函數private
,並且您的類之外的任何代碼都可以輕松創建打破Singleton范例的類的實例。
A類2:
看這段代碼:
public class A {
private static final A instance = new A();
private A(){}
public static A getInstance() {
return instance;
}
}
您將為每次getInstance()
調用返回相同的實例。現在您的類的行為類似於Singleton,實際上您正在此處急切地實例化Singleton實例,並且此Singleton實例應該是線程安全的。 同時將課程定為final
課程, final
使任何人都無法對其進行子分類並破壞Singleton。
在第一種情況下
每次創建
A
的新實例時。
* 第二種情況*
按照單噸模式,應為
public class A {
private static A instance = null;
private A() {
}
public static A getInstance() {
if(instance == null) {
instance = new A();
}
return instance;
}
}
類
A
維護對單例實例的靜態引用,並從靜態getInstance()方法返回該引用。
A 1類getInstance()是單例嗎?
否,因為每次調用此方法時,都會創建A
的新實例。
我還想知道這兩個A類getInstance()方法之間的區別是什么?
第一個getInstance()
將始終創建類A的新實例,第二個getInstance()
將始終返回創建類A的相同實例。
There are two ways of creating a singleton class
1, Dynamic Singleton
2, Static Singleton
Static Singleton :
public class A {
//Create a object of class A and make it final so that nobody can modify it
private static final A instance = new A();
//make the constructor private so that new objects can not be created
private A(){}
//provide a method to access the object
public static A getInstance() {
return instance;
}
}
Dynamic Singleton :
a, Single Check
public class A {
//Create a object reference of class A
private static A instance = null;
//make the constructor private so that new objects can not be created
private A() {}
public static A getInstance() {
//check if instance is null or not
if(instance == null) {
if(instance == null) {
//if null then create an instance of class A and assign it to the final reference
instance = new A();
}
}
return instance;
}
}
b, double check
public class A {
//Create a object reference of class A
private static A instance = null;
//make the constructor private so that new objects can not be created
private A() {}
public static A getInstance() {
//check if instance is null or not
if(instance == null) {
synchronized(A.class){
//Double Check
if(instance == null) {
//if null then create an instance of class A and assign it to the final reference
instance = new A();
}
}
}
return instance;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.