Singleton


Description:

A class of which only a single instance can exist

Intent:

  • Ensure a class has only one instance, and provide a global point of access to it.
  • Encapsulated "just-in-time initialization" or "initialization on first use".

Example:

Note

Idea:

Check list

  1. Define a private static attribute in the "single instance" class.
  2. Define a public static accessor function in the class.
  3. Do "lazy initialization" (creation on first use) in the accessor function.
  4. Define all constructors to be protected or private.
  5. Clients may only use the accessor function to manipulate the Singleton.

Code:

#include <iostream>
#include <memory>
#include <vector>
#include <cmath>

using namespace std;

class GlobalClass{
public:
    static GlobalClass * getInstance(){
        if(s_instance==nullptr){
            s_instance = new GlobalClass;
        }
        return s_instance;
    }

    int getVal(){
        return val;
    }

    void setVal(int v){
        val=v;
    }
private:
    GlobalClass(){}
    GlobalClass(const GlobalClass&);
    GlobalClass& operator=(const GlobalClass &);
    ~GlobalClass(){}  // Not sure if delete s_instance is OK?
    static GlobalClass * s_instance;
    // OR static unique_ptr<GlobalClass> s_instance;
    int val=0;
};

GlobalClass * GlobalClass::s_instance=nullptr;

int main(){
    cout<<GlobalClass::getInstance()->getVal()<<endl;
    GlobalClass::getInstance()->setVal(10);
    cout<<GlobalClass::getInstance()->getVal()<<endl;
    // unique_ptr<int> a = nullptr;
}

results matching ""

    No results matching ""