帐前卒专栏

Without software, we are nothing.

Software Architecture--Singleton

Singleton is a pattern in Software Architecture. It is used to create a instance and there will be only one instance in system at any time. If you want to write this pattern in a file, it will be like that:

[codesyntax lang=”cpp” tab_width=”2”]

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
31
32
33
34
#include <iostream>
using namespace std;
/* ==========================
 * Program name:
 * Author: chico chen
 * Email:  chillycreator @t gmail.com
 * Purpose: this class is testing singleton pattern in
 *          Software Architecture.
 * ========================== */

class Singleton {
  private:
  static Singleton* _instance;
  Singleton(){}
  public:
      static Singleton* Instance();
};
Singleton* Singleton::_instance = NULL;
Singleton* Singleton::Instance() {
    if (_instance == NULL) {
        _instance = new Singleton();
        cout <<"new Singleton"<<endl;
    }
    return _instance;
}

int main() {
    cout << "Hello world!" << endl;
    Singleton *s1 = Singleton::Instance();
    Singleton *s2 = Singleton::Instance();
    Singleton *s3 = Singleton::Instance();
    Singleton *s4 = Singleton::Instance();
    return 0;
}

If you want write this pattern into different files, it will has Singleton.h Singleton.cpp and other files like that:

Singleton.h

[codesyntax lang=”cpp” tab_width=”2”]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/* ==========================
 * Program name:
 * Author: chico chen
 * Email:  chillycreator @t gmail.com
 * Purpose: this class is testing singleton pattern in
 *          Software Architecture.
 * ========================== */

class Singleton {
  private:
  static Singleton* _instance;
  Singleton();
  public:
      static Singleton* Instance();
};

Singleton.cpp

[codesyntax lang=”cpp” tab_width=”2”]

1
2
3
4
5
6
7
8
9
10
#include "Singleton.h"
Singleton::Singleton(){}
Singleton* Singleton::_instance = NULL;
Singleton* Singleton::Instance() {
    if (_instance == NULL) {
        _instance = new Singleton();
        cout<<"new Singleton"<<endl;
    }
    return _instance;
}

main.cpp

[codesyntax lang=”cpp” tab_width=”2”]

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include "Singleton.h"
using namespace std;
int main() {
    cout << "Hello world!" << endl;
    Singleton *s1 = Singleton::Instance();
    Singleton *s2 = Singleton::Instance();
    Singleton *s3 = Singleton::Instance();
    Singleton *s4 = Singleton::Instance();
    return 0;
}

But it dose not ensure this instance is only the same in the system. Because it will be destroyed and recreated.

Comments