Featured Post

Trie implementation in C

Singleton Design Pattern

Here we present the implementation for a Singleton class.


//singleton.hpp
class Singleton
{
  private:
    int value;
    static Singleton *_instance;
    Singleton();
    Singleton(const Singleton&);
    Singleton & operator=(const Singleton &);
    ~Singleton();
    
  public:
    int getVal();
    void setVal(int);
    static Singleton* getInstance();
};

Singleton* Singleton::_instance;


//singleton.cpp
#include "singleton.hpp"
#include <iostream>

using namespace std;

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

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

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

int Singleton :: getVal()
{
  return value;  
}

void Singleton :: setVal(int val)
{
  value = val;
}

int main()
{
  Singleton::getInstance()->setVal(20);
  cout << Singleton::getInstance()->getVal();   
}


To run the program :
1. g++ -o singleton singleton.cpp (make sure that the header file singleton.hpp is in the same directory as singleton.cpp)
2. ./singleton

Comments