LintCode 204: Singleton

LintCode 204: Singleton

题目描述

单例是最为最常见的设计模式之一。对于任何时刻,如果某个类只存在且最多存在一个具体的实例,那么我们称这种设计模式为单例。例如,对于class Mouse(不是动物的mouse哦),我们应将其设计为singleton模式。

你的任务是设计一个getInstance方法,对于给定的类,每次调用getInstance时,都可得到同一个实例。

样例

Java中:

A a = A.getInstance();
A b = A.getInstance();

a应等于b.

Thu Mar 2 2017

思路

这题如果用C++写的话,需要注意的就是静态成员在使用前需要初始化,否则就会报错。

代码

// 单例
#include <iostream>
using namespace std;

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

Solution* Solution::_this = NULL;

int main(int argc, char** argv)
{
    Solution a;
    Solution b;
    cout << a.getInstance() << endl;
    cout << b.getInstance() << endl;

    return 0;    
}
posted @ 2017-03-02 17:05  GenkunAbe  阅读(318)  评论(0编辑  收藏  举报