寫程式時,常需載入些較占記憶體的檔案,像是圖像及影音載入,或執行需大量運算的物件,以圖片載入來說,假設我們需從檔案載入某張影像,如:
class ImageLoader {
prvate Image img;
public ImageLoader (File imgfile) {
img = Load(imgfile);
}
public void show() {
//To something to show image
}
}
一般,會將影像物件在建構時建立,但萬一此物件從未被使用,或是在系統運行一陣子之後,才會使用到,則我們可將上述程式改寫為:
class ImageLoader {
private Image img;
private File imgfile;
public ImageLoader (File imgfile) {
this.imgfile = imgfile;
}
public void show() {
if(img == null)
img = Load(imgfile); /*Load on show*/
//To something to show image
}
}
由上述程式碼可知,影像物件imgfile在顯示時才會載入(Load on Show)。所謂延遲初始化(Delay Initialization)即為物件在需要時才載入,可減少不必要的載入動作,但要注意的是,若載入的時間過長,可考慮使用多執行序,避免使用者等待程式反應時間過長,如:
class ShowImage extends Thread {
private ImageLoader imgloader;
public ShowImage(ImageLoader imgloader) {
this.imgloader = imgloader;
}
public void run() {
imgloader.show();
}
}
欲顯示影像時:
new ShowImage().start();
即可由另一執行序讀入影像檔案,減少使用者等待程式回應。
請先 登入 以發表留言。