java中单态模式或单例模式(Singleton)有什么意义?
.单态模式或单例模式(Singleton)
单态模式有什么用呢?想一下Adobe Photoshop ,处理两张图,会启动两个photoshop吗?多耗费内存呀! ( Consider Adobe or oracle, process two images with two adobes?),所以单态模式在公司编程是非常重要的。有很多场合都要求,对象只能存在一个,多了的话就太耗费资源。(马克-to-win)
马克- to-win:马克 java社区:防盗版实名手机尾号: 73203。
class Photoshop {
/* 通过调试发现写成 static Photoshop photoshop或static Photoshop
photoshop=null;是一样的,开始时都为null,马克-to-win,另外在调试时 可以写上观察Photoshop.photoshop的值,它是独立于任何对象之外的,从程序开始运行的main方法时, 这个值就有了, 只不过为null罢了,
*/
static Photoshop photoshop;//这个值独立于任何对象存在,实例化任何对象之前,这个成员就有可能有值。
static Photoshop getInstanceQixy() {
if (photoshop == null) {
photoshop = new Photoshop();
System.out.println("成功创建");
} else {
System.out.println("已经创建了该类的实例,不能再创建!");
}
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:
成功创建
已经创建了该类的实例,不能再创建!
true
true
draw image using photoshop
false
反思一下: 如果写成:static Photoshop photoshop=new Photoshop();程序执行到main时,实例化就被执行了,而现在会在Photoshop.getInstanceQixy();时才对象实例化。执行的时机不一样。有时可能不用初始化的这么早。
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."