模板(四)

用模板实现单例模式

方法1

#ifndef _SINGLETON_H_
#define _SINGLETON_H_


template <typename T>
class Singleton
{
public:
    static T& GetInstance()    //静态成员函数,全局
    {
        static T instance;     //创建一个静态局部对象
                               //此处必须要static,否则构造完成,就析构了
        return instance;
    }
private:
    Singleton();
    Singleton(const Singleton& other);
    Singleton& operator= (const Singleton& other);
    ~Singleton();

    //static T* instance_;
};

//template <typename T>
//T* Singleton<T>::instance_ = 0;
#endif // _SINGLETON_H_
#include "Singleton.h"
#include<iostream>

using namespace std;
class ApplicationImpl
{
public:
    ApplicationImpl()
    {
        cout << "ApplicationImpl..." << endl;
    }
    ~ApplicationImpl()
    {
        cout << "~ApplicationImpl..." << endl;
    }
    void Run()
    {
        cout << "Run ..." << endl;
    }
private:
};

typedef Singleton<ApplicationImpl> Application;
int main(void)
{
    //Singleton<ApplicationImpl> a;  //Error : 由于Singleton构造函数时私有的,无法访问,就无法用Singleton来构造对象
    Application::GetInstance().Run();
    Application::GetInstance().Run();
    return 0;
}

这里写图片描述

方法2(推荐)


  • atexit()函数

    用atexit()函数,该函数为注册函数,可以将其它函数注册进来。在程序结束后,会先调用注册的函数,再结束程序,优先调用后注册的函数

    包含的头文件: < cstdlib >


#ifndef _SINGLETON_H_
#define _SINGLETON_H_

#include<cstdlib>
using namespace std;

template <typename T>
class Singleton
{
public:
    static T& GetInstance()    //静态成员函数,全局
    {
        Init();
        return *instance_;
    }
private:
    static void Init()
    {
        if (instance_ == 0)
        {
            instance_ = new T;
            atexit(Destory);
        }
    }
    static void Destory()
    {
        delete instance_;
    }
    static T* instance_;
    Singleton();
    Singleton(const Singleton& other);
    Singleton& operator= (const Singleton& other);
    ~Singleton();
};

template <typename T>
T* Singleton<T>::instance_ = 0;    //static成员需在外部初始化

#endif // _SINGLETON_H_
#include "Singleton.h"
#include<iostream>

class ApplicationImpl
{
public:
    ApplicationImpl()
    {
        cout << "ApplicationImpl..." << endl;
    }
    ~ApplicationImpl()
    {
        cout << "~ApplicationImpl..." << endl;
    }
    void Run()
    {
        cout << "Run ..." << endl;
    }
};

typedef Singleton<ApplicationImpl> Application;
int main(void)
{
    //Singleton<ApplicationImpl> a;  //Error : 由于Singleton构造函数时私有的,无法访问,就无法用Singleton来构造对象
    Application::GetInstance().Run();
    Application::GetInstance().Run();
    return 0;
}

这里写图片描述

模板动态创建对象

见72cpp

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值