TITLe:How to create singleton class in Symbian
What is Singleton class??
A class whose number of instances that can be instantiated is limited to one is called a singleton class. Thus, at any given time only one instance can exist.
How to implement it in symbian??
Symbian provided CCoeStatic base class for creating singleton class. To omplement singleton pattern you have to derive your class from CCoeStatic class.
for example:
//MySingleton.h
#include <coemain.h>
class CMySingleton: public CCoeStatic
{
public:
static CMySingleton* GetInstance();
~CMySingleton();
private:
CMySingleton();
void InitializeL();
public:
void UpdateData(const TDesC8& aText);
TInt iNumber;
}
//MySingleton.cpp
static const TUid KUidMySingleton = { 0x10000123 };
CMySingleton* CMySingleton::GetInstance()
{
CMySingleton* pInstance = (CMySingleton*)CCoeEnv::Static(KUidMySingleton);
if (!pInstance)
{
pInstance = new (ELeave) CMySingleton();
pInstance->InitializeL();
}
return pInstance;
}
CMySingleton::~CMySingleton()
{
}
CMySingleton::CMySingleton():CCoeStatic(KUidMySingleton)
{
}
void CMySingleton::InitializeL()
{
iNumber = 8; //initialize data member here.
}
void CMySingleton::UpdateData(const TDesC8& aText)
{
}
you can make to a temple
template <class aType, TInt aUid> class CMySingleton: public CCoeStatic
{
TYPE iInstance;
CSingleton() : CCoeStatic( TUid::Uid(aUid) ) {}
public:
/**
Answer a location to hold a static variable of type TYPE.
UID must be a unique ID (preferably allocated by Symbian).
*/
static TYPE& GetL()
{
CSingleton<aType, aUid>* staticData = static_cast<CSingleton<aType, aUid>* >(CCoeEnv::Static(TUid::Uid(aUid)));
if (staticData)
return staticData->iInstance;
//CCoeStatic会处理内存释放的问题
staticData = new (ELeave) CMySingleton<aType, aUid>;
return staticData->iInstance;
}
};
you can use as follow:
const TInt KASingletomUid = 1;
class A;
CMySingleton<A, KASingletomUid > ASigleton;
ASigleton::GetL();