[LintCode][System Design] Single

作者: 楷书 | 来源:发表于2016-03-26 02:24 被阅读206次

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;

相关文章

网友评论

    本文标题:[LintCode][System Design] Single

    本文链接:https://www.haomeiwen.com/subject/jssdlttx.html