java中单态模式或单例模式(Singleton)有什么意义?
8.单态模式或单例模式(Singleton)
单态模式有什么用呢?想一下Adobe
Photoshop ,处理两张图,会启动两个photoshop吗?多耗费内存呀! ( Consider Adobe or oracle,
process two images with two
adobes?),所以单态模式在公司编程是非常重要的。有很多场合都要求,对象只能存在一个,多了的话就太耗费资源。(马克-to-win)
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);
}
}
更多内容请见原文,原文转载自:https://blog.csdn.net/qq_44639795/article/details/103125543