An implementation of the singleton pattern must:
- ensure that only one instance of the singleton class ever exists; and
- provide global access to that instance.
#include <string> class Singleton { static Singleton* s; std::string onlyOne; Singleton(); public: Singleton(const Singleton&) = delete; Singleton& operator=(const Singleton&) = delete; ~Singleton(); static Singleton* getInstance(); void setSingleton(const std::string &st); std::string getSingelton(); };You need to disable the copy constructor.
Now let's create the .h Singleton header file.
#include <string> class Singleton { static Singleton* s; std::string onlyOne; Singleton(); public: Singleton(const Singleton&) = delete; Singleton& operator=(const Singleton&) = delete; ~Singleton(); static Singleton* getInstance(); void setSingleton(const std::string &st); std::string getSingelton(); };Now let's put this all together in main method in the main.cpp file
#include <iostream> #include "Singleton.h" using std::cout; using std::endl; int main(int argc, char* argv[] ) { cout << "The Ray Code is AWESOME!!" << endl; cout << "The value is the " << Singleton::getInstance()->getSingelton() << endl; Singleton::getInstance()->setSingleton("Changed Value"); cout <<"The value is the " << Singleton::getInstance()->getSingelton() << endl; return 0; }Let's compile and run:
The value is the Original Value The value is the Changed Value
The Ray Code is AWESOME!!!
wikipedia
Find Ray on:
youtube
The Ray Code
Ray Andrade