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;    
}

转载于:https://www.cnblogs.com/genkun/p/6491540.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值