c++ python实现 单例 singleton

17 篇文章 0 订阅
15 篇文章 0 订阅

首先是通过了Lintcode测试的,九章算法提供的代码

/**
 * 本代码由九章算法编辑提供。没有版权欢迎转发。
 * - 九章算法致力于帮助更多中国人找到好的工作,教师团队均来自硅谷和国内的一线大公司在职工程师。
 * - 现有的面试培训课程包括:九章算法班,系统设计班,九章强化班,Java入门与基础算法班
 * - 更多详情请见官方网站:http://www.jiuzhang.com/
 */

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;

然后是stackoverflow上面比较好的代码:(注意返回的是引用!而且是使用静态方法和静态成员变量!)

class S
{
    public:
        static S& getInstance()
        {
            static S    instance; // Guaranteed to be destroyed.
                                  // Instantiated on first use.
            return instance;
        }
    private:
        S() {};                   // Constructor? (the {} brackets) are needed here.

        // C++ 03
        // ========
        // Dont forget to declare these two. You want to make sure they
        // are unacceptable otherwise you may accidentally get copies of
        // your singleton appearing.
        S(S const&);              // Don't Implement
        void operator=(S const&); // Don't implement

        // C++ 11
        // =======
        // We can use the better technique of deleting the methods
        // we don't want.
    public:
        S(S const&)               = delete;
        void operator=(S const&)  = delete;

        // Note: Scott Meyers mentions in his Effective Modern
        //       C++ book, that deleted functions should generally
        //       be public as it results in better error messages
        //       due to the compilers behavior to check accessibility
        //       before deleted status
};

还有一些参考文章:

其中有python实现的例子,如装饰器实现和import实现

def singleton(cls, *args, **kw):
    instances = {}
    def getinstance():
        if cls not in instances:
            instances[cls] = cls(*args, **kw)
        return instances[cls]
    return getinstance

@singleton
class MyClass:
  ...
# mysingleton.py
class My_Singleton(object):
    def foo(self):
        pass

my_singleton = My_Singleton()

# to use
from mysingleton import my_singleton

my_singleton.foo()

目前还是没有很透彻的理解,先把这些记录下来,希望以后再看能深刻理解吧。

更新,重复练习,进一步理解装饰器实现的单例模式

def singleton(cls):
    instance = {}
    def getInstance(*args, **kw):
        if cls not in instance:
            instance[cls] = cls(*args, **kw)
        return instance[cls]
    return getInstance

@singleton
class SC:
    def __init__(self, num):
        self.num = num

    def foo(self):
        print 'SC.foo'

class C:
    def foo(self):
        print 'C.foo'

if __name__ == '__main__':
    c1 = C()
    c2 = C()
    print 'id of c1: ', id(c1)
    print 'id of c2: ', id(c2)
    sc1 = SC(1)
    sc2 = SC(2)
    print 'id of sc1: ', id(sc1)
    print 'id of sc2: ', id(sc2)
    print 'sc1.num: ', sc1.num
    print 'sc2.num: ', sc2.num

输出:

id of c1:  4336506136
id of c2:  4336506208
id of sc1:  4336506280
id of sc2:  4336506280
sc1.num:  1
sc2.num:  1

可见,使用了装饰器singleton之后两次生成的实例其实是同一个,id相同,而且只能初始化第一次。num=1。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值