我想到的有这么几种方法
1、
Class SingleInstance {
private static SingleInstance instance = new SingleInstance();
private SingleInstance() {}
public SingleInstance getInstance() {
return instance;
}
}
任何需要取得instance的地方调用getInstance方法
2、
Class SingleInstance {
public SingleInstance() {}
}
在HttpServlet.init()方法中
SingleInstance instance = SingleInstance();
getServletContext().setAttribute("INSTANCE", instance);
任何需要取得instance的地方调用
getServletContext().getAttribute("INSTANCE");
如果在应用中只存在唯一的Servlet类响应客户端的请求。
请问后一种的线程安全性有没有问题?
其他方面这两种方式有没有区别?