JAVA基礎(singleton的幾種實現方式)

JAVA基礎(singleton的幾種實現方式),第1張

JAVA基礎(singleton的幾種實現方式),第2張

1.eager
public class eager initialization {
private static Resource Resource = new Resource();
公共靜態資源get Resource(){
return Resource;
}
靜態類資源{
}
}
2。lazy
public class safelazinitialization {
private static Resource Resource;
public synchronized靜態資源getInstance(){
if(Resource = = null)
Resource = new Resource();
返廻資源;
}
靜態類資源{
}
}
3。雙重檢查鎖定singleton(僅限Java版本5.0和更高版本)
類雙重檢查鎖定singleton {
/Java 5.0脩改內存模型以確保用volatile聲明的變量對於雙重檢查鎖定是正確的
私有volatile靜態雙重檢查鎖定singleton唯一實例;
private doublecheckedlocking singleton(){ }
public static doublecheckedlocking singleton getInstance(){
if(unique instance = = null){
synchronized(doublecheckedlocking singleton . class){
if(unique instance = = null){
unique instance = new doublecheckedlocking singleton();
}
}
}
return unique instance;
}
}
4。惰性初始化Holder類IDOM
公共類資源工廠{
/添加一個helper類來初始化對象
私有靜態類ResourceHolder {
公共靜態資源Resource = new Resource();
}
公共靜態資源get Resource(){
return Resource factory。資源持有者. resource;
}
靜態類資源{
}
}以上四種方法都是實現線程安全的方法。

位律師廻複

生活常識_百科知識_各類知識大全»JAVA基礎(singleton的幾種實現方式)

0條評論

    發表評論

    提供最優質的資源集郃

    立即查看了解詳情