建立專案情境 16 -- Keep on designing V
終於知道單例模式 Singleton Design Pattern,在Method getInstance()內,會有if(instance == null){instance = new Singleton();}這行Code !!!:
public static Singleton getInstance(){
if(instance == null){
instance = new Singleton();
}
return instance;
}
原因有二:
1. 假如建立這個物件需要耗費很多資源,可是程式運行中不一定會需要它,我們希望只有在第一次getInstance被呼叫的時候才花費資源來建立物件,code就要修改一下
(ref : https://skyyen999.gitbooks.io/-study-design-pattern-in-java/content/singleton.html)
2. 若欲建立單例模式 Singleton Design Pattern的Class(e.g. : Singleton), 其Super Class的Contructor(),有throws some execption,那麼,在Singleton的宣告區宣告並初始private static Singleton instance = new ChatServer();會發生Unhandled exception type RemoteException的錯誤,
第一步解法為:
private static Singleton instance = null;
{
Singleton instance = new Singleton();
}
但,Call Singleton的程式在呼叫單例模式 Singleton Design Pattern的getInstance()時
public static Singleton getInstance(){
return instance;
}
取得的instance會是:null。
所以要改成:
public static Singleton getInstance(){
if(instance == null){
instance = new Singleton();
}
return instance;
}
終於知道單例模式 Singleton Design Pattern,在Method getInstance()內,會有if(instance == null){instance = new Singleton();}這行Code !!!:
public static Singleton getInstance(){
if(instance == null){
instance = new Singleton();
}
return instance;
}
原因有二:
1. 假如建立這個物件需要耗費很多資源,可是程式運行中不一定會需要它,我們希望只有在第一次getInstance被呼叫的時候才花費資源來建立物件,code就要修改一下
(ref : https://skyyen999.gitbooks.io/-study-design-pattern-in-java/content/singleton.html)
2. 若欲建立單例模式 Singleton Design Pattern的Class(e.g. : Singleton), 其Super Class的Contructor(),有throws some execption,那麼,在Singleton的宣告區宣告並初始private static Singleton instance = new ChatServer();會發生Unhandled exception type RemoteException的錯誤,
第一步解法為:
private static Singleton instance = null;
{
Singleton instance = new Singleton();
}
但,Call Singleton的程式在呼叫單例模式 Singleton Design Pattern的getInstance()時
public static Singleton getInstance(){
return instance;
}
取得的instance會是:null。
所以要改成:
public static Singleton getInstance(){
if(instance == null){
instance = new Singleton();
}
return instance;
}
