什么是单例模式:
在应用系统开发中,我们常常有以下需求:
- 在多个线程之间,比如servlet环境,共享同一个资源或者操作同一个对象- 在整个程序空间使用全局变量,共享资源
- 大规模系统中,为了性能的考虑,需要节省对象的创建时间等等。
因为Singleton模式可以保证为一个类只生成唯一的实例
对象,所以这些情况,Singleton模式就派上用场了。
案例:
public class Person {
private static Person person;
private Person() {
}
public static Person getInstance1() {
if (person == null) {
person = new Person();
}
return person;
}
public static synchronized Person getInstance2() {
if (person == null) {
person = new Person();
}
return person;
}
}
测试: