java中單態(tài)模式或單例模式(Singleton)有什么意義?
.單態(tài)模式或單例模式(Singleton)
單態(tài)模式有什么用呢?想一下Adobe Photoshop ,處理兩張圖,會(huì)啟動(dòng)兩個(gè)photoshop嗎?多耗費(fèi)內(nèi)存呀! ( Consider Adobe or oracle, process two images with two adobes?),所以單態(tài)模式在公司編程是非常重要的。有很多場(chǎng)合都要求,對(duì)象只能存在一個(gè),多了的話就太耗費(fèi)資源。(馬克-to-win)
馬克- to-win:馬克 java社區(qū):防盜版實(shí)名手機(jī)尾號(hào): 73203。
class Photoshop {
/* 通過(guò)調(diào)試發(fā)現(xiàn)寫成 static Photoshop photoshop或static Photoshop
photoshop=null;是一樣的,開(kāi)始時(shí)都為null,馬克-to-win,另外在調(diào)試時(shí) 可以寫上觀察Photoshop.photoshop的值,它是獨(dú)立于任何對(duì)象之外的,從程序開(kāi)始運(yùn)行的main方法時(shí), 這個(gè)值就有了, 只不過(guò)為null罷了,
*/
static Photoshop photoshop;//這個(gè)值獨(dú)立于任何對(duì)象存在,實(shí)例化任何對(duì)象之前,這個(gè)成員就有可能有值。
static Photoshop getInstanceQixy() {
if (photoshop == null) {
photoshop = new Photoshop();
System.out.println("成功創(chuàng)建");
} else {
System.out.println("已經(jīng)創(chuàng)建了該類的實(shí)例,不能再創(chuàng)建!");
}
return photoshop;
}
void drawImage() {
System.out.println("draw image using photoshop");
}
}
public class Test {
public static void main(String[] args) {
Photoshop photoshopI1 = Photoshop.getInstanceQixy();
Photoshop photoshopI2 = Photoshop.getInstanceQixy();
System.out.println(photoshopI1 == photoshopI2);
System.out.println(photoshopI1 == Photoshop.photoshop); photoshopI1.drawImage();
Photoshop photoshopI3 = new Photoshop();
System.out.println(photoshopI1 == photoshopI3);
}
}
result is:
成功創(chuàng)建
已經(jīng)創(chuàng)建了該類的實(shí)例,不能再創(chuàng)建!
true
true
draw image using photoshop
false
反思一下: 如果寫成:static Photoshop photoshop=new Photoshop();程序執(zhí)行到main時(shí),實(shí)例化就被執(zhí)行了,而現(xiàn)在會(huì)在Photoshop.getInstanceQixy();時(shí)才對(duì)象實(shí)例化。執(zhí)行的時(shí)機(jī)不一樣。有時(shí)可能不用初始化的這么早。
class Photoshop {
static Photoshop photoshop=new Photoshop();
static Photoshop getInstanceQixy() {
return photoshop;
}
void drawImage() {
System.out.println("draw image using photoshop");
}
}
public class Test {
public static void main(String[] args) {
Photoshop photoshopI1 = Photoshop.getInstanceQixy();
Photoshop photoshopI2 = Photoshop.getInstanceQixy();
System.out.println(photoshopI1 == photoshopI2);
photoshopI1.drawImage();
Photoshop photoshopI3 = new Photoshop();
System.out.println(photoshopI1 == photoshopI3);
}
}
Assignment: make a photoshop instance using Singleton, call its method of drawImage(), additional requiredment:after the first time to activate the photoshop, from the second time on, when you activate it, it will print "you have already activate one photoshop."