204. 单例
单例 是最为最常见的设计模式之一。对于任何时刻,如果某个类只存在且最多存在一个具体的实例,那么我们称这种设计模式为单例。例如,对于 class Mouse (不是动物的mouse哦),我们应将其设计为 singleton 模式。
你的任务是设计一个 getInstance 方法,对于给定的类,每次调用 getInstance 时,都可得到同一个实例。
样例
在 Java 中:
A a = A.getInstance();
A b = A.getInstance();
a 应等于 b.
挑战
如果并发的调用 getInstance,你的程序也可以正确的执行么?
class Solution {
public:
/**
* @return: The same instance of this class every time
*/
static Solution* sigle;
static Solution* getInstance() {
// write your code here
if(sigle==NULL)
{
sigle=new Solution();
}
return sigle;
}
};
Solution* Solution::sigle=NULL;
############################################################
class Solution:
# @return: The same instance of this class every time
instance=None
@classmethod
def getInstance(cls):
# write your code here
if cls.instance==None:
cls.instance=Solution()
return cls.instance
本文深入探讨了单例设计模式的概念,解释了如何确保一个类只有一个实例,并提供了在并发环境下实现单例模式的方法。通过示例代码,展示了在C++和Python中如何正确地使用单例模式。
844

被折叠的 条评论
为什么被折叠?



