کلاس Single Tone ژنریک با استفاده از اشاره گرهای هوشمند برای ساخت آبجکتی از یک کلاس با یک نمونه واحد. سازگار با کامپایلر GCC

#ifndef SINGLETON_H
#define SINGLETON_H

#include <memory>

namespace BP {

template<typename CL>
class SingleTone {
protected:
SingleTone() = default; // defualt ctor
virtual inline ~SingleTone(){
delete instance;
}

private:
static CL* instance;

SingleTone(const SingleTone&) = delete; //copy ctor
SingleTone(SingleTone&&) = delete ; //move ctor
SingleTone& operator=(const SingleTone&) =delete ; // copy oprator assignment
SingleTone& operator=(SingleTone&&) =delete ; // move oprator assignment


static void destory(CL* my){
delete my ;
instance = NULL;
}

public:
std::unique_ptr<CL , decltype(&destory)> factory(){
//lazy instation
if(instance == NULL){
instance = new CL();
}
return std::unique_ptr<CL , decltype(&destory)>(instance , &destory);
}

};

template<typename CL>
CL* SingleTone<CL>::instance = NULL;

}

#endif // SINGLETON_H

ونحوه استفاده از کلاس فوق من کلاسی دارم برای ارتباط با پایگاه داده به نام DBProvider که در این کلاس متدی به نام OpenConnection را صدا زدم.
توجه کنید که هر کلاسی که بخواهید را می توانید به حالت single tone ایجاد نمایید.
روش اول فراخوانی

db = SingleTone<DBProvider>::factory ()->OpenConnection ()

روش دوم فراخوانی

db = (*SingleTone<DBProvider>::factory ()).OpenConnection ();

فقط توجه داشته باشید که آبجکتهایی که single tone هستند یک اشاره گر واحد دارند بنابراین در کل برنامه یکسان خواهند بود.

کلاس SingleTone سازگار با کامپایل VisualC++‎‎‎14

#pragma once
#include <memory>

template<class T>
class SingleTone
{

private:

SingleTone() = default;
inline ~SingleTone() {
destory(m_instance);
};

public:
SingleTone(const SingleTone&) = delete; //copy ctor
SingleTone(SingleTone&&) = delete; //move ctor
SingleTone& operator=(const SingleTone&) = delete; // copy oprator assignment
SingleTone& operator=(SingleTone&&) = delete; // move oprator assignment

static void destory(T* my) {
delete my;
}

static std::unique_ptr<T ,decltype(&destory)>& getUniquePInstance() {
static T* m_instance = new T;
return std::unique_ptr<T, decltype(&destory)>(std::reference_wrapper<T*>(m_i nstance), &destory);
}

};