我想测试一个单例类只创建一个单一的对象。 如何测试班级。如何测试单例类只创建一个对象
下面的代码
Singleton类: -
public class SpringApplicationContext {
private static ClassPathXmlApplicationContext context = null;
private SpringApplicationContext(){};
public static ClassPathXmlApplicationContext getInstance() {
if (context == null) {
context = new ClassPathXmlApplicationContext(
"spring.xml");
}
return context;
}
}
调用类: -
public static void main(String[] args) {
ClassPathXmlApplicationContext ctx = SpringApplicationContext.getInstance();
System.out.println("yup");
}
多次调用'getInstance'并检查引用上的== ==是否返回true。对于复合对象,您将必须检查单例内的每个引用类型。 – TheLostMind
请注意,您的实现不是线程安全的。也就是说,两个线程可以导致创建两个实例。 – johnnyaug
@TheLostMind - 何时会返回true。只有比较两个参考时,它才会返回true。 –