10001:Chromium单例模式实现方式

来源:互联网 发布:网络视频传播许可证 编辑:程序博客网 时间:2024/05/16 13:48

先写实例,分析流程,最后分析源码和原理。

1、首先是demo代码

class CSingletonDemo   {public:    CSingletonDemo();    ~CSingletonDemo();    static CSingletonDemo* GetInstance();};CSingletonDemo::CSingletonDemo(){}CSingletonDemo::~CSingletonDemo(){}CSingletonDemo* CSingletonDemo::GetInstance(){    return Singleton<CSingletonDemo>::get();}

2、分析

  • 首先定义一个静态成员函数,保证返回的是同一个对象
  • 对Singleton进行特化,通过get函数获取特化后的结果

3、 SingleTon源码和简单分析

template <typename Type,          typename Traits = DefaultSingletonTraits<Type>,          typename DifferentiatingType = Type>class Singleton { private:     friend Type* Type::GetInstance();     static Type* get() {        ...     }}
  • 由于get()是私有的,同时又定义了友元函数friend Type* Type::GetInstance(),所以,在使用Singleton的class中,必须定义GetInstance(),才能以友元的方式访问get,获取对象实例。
0 0
原创粉丝点击