單例模式的三種優雅實現方法
阿新 • • 發佈:2019-01-28
單例模式常用是Double Check
public class singletonObject{
private static singletonObject instance;
private singletonObject(){}
public static singletonObject getInstance(){
if(null==instance){
sysnchronized(singletonObject.class){
if(null==instance){
instance=new singletonObject();
}
}
}
return instance;
}
}
這個既可以實現延遲載入和效能的提高,但是會有一個危險,但例項化內容較多時,進行到一半另一個執行緒就返回了,這個時候就會造成空指標異常
優雅解決這個問題的三種方法:
使用關鍵字volatile
用來確保將變數的更新操作通知到其他執行緒,具體如下:
public class singletonObject{
private static volatile singletonObject instance;
private singletonObject(){}
public static singletonObject getinstance(){
if(null==instance){
sysnchronized(singletonObject.class){
if(null==sysnchronized){
instance=new singletonObject();
}
}
}
return instance;
}
}
加一個靜態類來實現例項化
public class singletonObject{
private singletonObject(){}
private static class InstanceHolder{
private final static singletonObject instance=new singletonObject();
}
public static singletonObject(){
return InstanceHolder.instance;
}
}
列舉法
這個即保證了效能又絕對的安全 ,列舉是執行緒安全的
packagecom.dmsdbj.itoo.teachingManagement.service.impl;
importsun.swing.plaf.synth.DefaultSynthStyle;
importjava.util.stream.IntStream;
/**
*CreatedbyAdministratoron2018/4/180018.
*/
publicclassSingletonObject{
privateSingletonObject(){}
public enum Singletos{
INSTANCE;
private final SingletonObject instance;
Singletos(){
instance=new SingletonObject();
}
public SingletonObjectget Instance(){
return instance;
}
}
public static SingletonObjectget Instance(){
return Singletos.INSTANCE.getInstance();
}
public static void main(String[]args){
IntStream.rangeClosed(1,100).forEach(i->newThread(String.valueOf(i)){
@Override
public void run(){
System.out.print(SingletonObject.getInstance()+"\n");
}
}.start());
}
}
讓我們多學習優秀的程式碼,做一個安靜的優秀美男子