Java細節-陣列和String的轉換
阿新 • • 發佈:2021-01-21
單例模式
未完待續
//懶漢式執行緒不安全
public class Singleton {
private static Singleton instance;
private Singleton(){}
public static Singleton getInstance(){
if(instance==null){
instance=new Singleton();
}
return instance;
}
}
//懶漢式執行緒安全
class Singleton01 {
private static Singleton01 instance;
private Singleton01(){}
public static synchronized Singleton01 getInstance(){
if(instance==null){
instance=new Singleton01();
}
return instance;
}
}
/**
* 餓漢式
* 容易產生垃圾物件
*/
class Singleton02{
private static Singleton02 instance= new Singleton02();
private Singleton02(){}
public static Singleton02 getInstance(){
return instance;
}
}
/**
* 雙重校驗鎖
*/
class Singleton03{
private volatile static Singleton03 singleton03;
private Singleton03(){}
public static Singleton03 getSingleton03(){
if(singleton03== null){
synchronized (Singleton.class){
if(singleton03==null){
singleton03=new Singleton03();
}
}
}
return singleton03;
}
}