Singleton 204
Question
Singleton is a most widely used design pattern. If a class has and only has one instance at every moment, we call this design as singleton. For example, for class Mouse (not a animal mouse), we should design it in singleton.
You job is to implement a getInstance method for given class, return the same instance of this class every time you call this method.
Solution
单例模式,要考虑并发情况。
为了防止多个线程创建多个实例,要在new之前加一个锁,即synchronized。同时为了防止多个线程在判断实例为null之后先后进入synchronized依然创建多个实例,可以在synchronized之后double check一下实例是否为null。更多讨论见下:
代码如下:
class Solution {
/**
* @return: The same instance of this class every time
*/
//考察静态变量
public static Solution s = null;
public static Solution getInstance() {
// write your code here
if(s == null){
synchronized (Solution.class){
if(s == null){
s = new Solution();
}
}
}
return s;
}
};