LintCode_204 Singleton

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();

定義一個靜態變量來解決:


class Solution {
public:
    /**
     * @return: The same instance of this class every time
     */
    static Solution* instance;
    static Solution* getInstance() {
        if (instance == NULL) {
            instance = new Solution();
        }
        return instance;
    }
};

Solution* Solution::instance = NULL;




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章