[LintCode][System Design] Singleton

Problem

More LeetCode Discussions

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.

Example

In Java:

A a = A.getInstance();
A b = A.getInstance();
a should equal to b.

Challenge

If we call getInstance concurrently, can you make sure your code could run correctly?

Solution

#include <mutex>

class Solution {
public:
    /**
     * @return: The same instance of this class every time
     */
    static Solution* getInstance() {
        static Solution *instance = NULL;
        if (instance == NULL) {
            mtx.lock(); // lock is used to keep to create only one instance when concurrently getInstance()
            if (instance == NULL) {
                instance = new Solution();
            }
            mtx.unlock();
        }
        return instance;
    }
private:
    static std::mutex mtx;
};

std::mutex Solution::mtx;
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,349评论 0 33
  • 受了这么多年的正统教育,对于越雷池半步之事,基本可以做到下意识不逾矩,在一个群体里,如果有可能,我更愿意做最沉默安...
    小花fayer阅读 2,929评论 5 3
  • 那天的你穿了一件我喜欢的天蓝色的衬衫,戴着我喜欢的黑框眼镜,留着我喜欢的发型,嘴角有点笑,你站在桌旁看着我,窗外...
    南遥思故阅读 2,895评论 2 15
  • 公众号:OMG24 原创 朋友前妻小A和朋友是通过QQ在网上认识的,朋友北京人211大学毕业,他俩认识的时候朋友已...
    蛋糕妈琐事阅读 3,764评论 0 0
  • 娃问我,妈妈,我出生的那一天也是这样纷纷扬扬下着雪吗? 我说,憨娃,十二年前的晚上能和今晚一样吗? 娃又问,那我出...
    那年凌汛阅读 1,501评论 0 0