Tuesday

Software Design Patterns: Singleton pattern using C++

Why?

Ensure a class only has one instance and provide a global point of access to it.

 

Code:

#include <iostream>
using namespace std;

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

Singleton* Singleton::_instance = 0;

Singleton::Singleton() {
cout << "Singleton::Singleton()" << endl;
}

Singleton* Singleton::getInstance() {
if (_instance == 0) {
_instance = new Singleton;
}
return _instance;
}

int main()
{
Singleton* singleton = Singleton::getInstance();
}


Sample run:

Singleton::Singleton()

No comments:

Measure execution time with Julia, example using sorting algorithms

# random integers between 1 and 100 inclusive, generate thousands of them x = rand ( 1 : 100 , 100000 ) @time sort (x; alg=InsertionSort, r...