Design Pattern

单例模式

  1. 将构造函数、拷贝构造函数和赋值符号函数私有化
  2. 在类中定义一个静态的指向本类型的指针变量
  3. 定义一个返回值为类指针的静态成员函数
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    class Singleton {
    public:
    static Singleton * getInstance(){
    if(nullptr == _pInstance)
    { _pInstance = new Singleton(); }
    return _pInstance;
    }
    static void Delete(){
    if(_pInstance)
    delete _pInstance;
    }
    private:
    Singleton() {}
    Singleton(Singleton &other){}
    void operator=(const Singleton &) {}
    private:
    Static Singleton * _pInstance;
    };
    Singleton * Singleton::_pInstance = nullptr;

这样不是自动释放

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Singleton
{
private:
static Singleton* instance;
private:
Singleton() { };
~Singleton() { };
Singleton(const Singleton&);
Singleton& operator=(const Singleton&);
private:
class Deletor {
public:
~Deletor() {
if(Singleton::instance != NULL)
delete Singleton::instance;
}
};
static Deletor deletor;
public:
static Singleton* getInstance() {
if(instance == NULL) {
instance = new Singleton();
}
return instance;
}
};

// init static member
Singleton* Singleton::instance = NULL;
Singleton::Deletor Singleton::deletor;

Reference: C++ 单例模式