单例

单例 是最为最常见的设计模式之一。对于任何时刻,如果某个类只存在且最多存在一个具体的实例,那么我们称这种设计> 模式为单例。例如,对于 class Mouse (不是动物的mouse哦),我们应将其设计为 singleton 模式。
你的任务是设计一个getInstance方法,对于给定的类,每次调用getInstance时,都可得到同一个实例。

样例

在 Java 中:
A a = A.getInstance();
A b = A.getInstance();
a 应等于 b.

挑战

如果并发的调用 getInstance,你的程序也可以正确的执行么?

标签

LintCode 版权所有 面向对象设计

code

class Solution {
public:
    /**
     * http://www.lintcode.com/zh-cn/ladder/6/-第2章-单例
     * @return: The same instance of this class every time
     */
    static Solution* getInstance() 
    {
        static bool ex = false;
        static Solution* one;
        if (ex == false)
        {
             one = new Solution();
             ex = true;
             return one;
        }
        else
            return one;
    }
};

相关文章:

  • 2022-12-23
  • 2021-11-20
  • 2022-01-18
猜你喜欢
  • 2022-02-02
  • 2022-02-13
  • 2021-09-02
  • 2021-08-13
  • 2021-10-07
  • 2021-12-02
  • 2021-09-19
相关资源
相似解决方案