How to create singleton

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();

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值