Oct 18, 2010

singleton pattern 和 wrapper class

singleton
class singleton
{
public:
 void print();
 static singleton &getSingleton(); //necessary
protected:

private:
 singleton();//necessary
 ~singleton() {}//necessary
 static int count;

};

int singleton::count = 0;

singleton::singleton()
{
 count ++;
}

void singleton::print()
{
 printf("%d\n",count);
}


singleton & singleton::getSingleton()//necessary
{
 static singleton ms;
 return ms;
}
1. private 构造和析构函数
2. public 函数返回 static 成员的引用

wrapper 类例子
month 类
class Month
{
public:
 static Month Jan() { return Month(1); }
 static Month Feb() { return Month(2); }

private:
 explicit Month(int m):month(m) {}
 int month;

};

0 comments: