Write a program to use of singleton pattern.
#include<iostream> using namespace std; class A { public: static bool flag; static A* get_obj(); void fun() { cout << "function" << endl; } }; bool A :: flag = false; A* A :: get_obj() { static A *p; if(flag == false) { cout << "Created new" << endl; p = new A; flag = true; return p; } else { cout << "Same" << endl; return p; } } int main() { A *ob1,*ob2,*ob3,*ob4,*ob5; ob1 = A :: get_obj(); ob1->fun(); cout << ob1 << endl; ob2 = A :: get_obj(); ob2->fun(); cout << ob2 << endl; ob3 = A :: get_obj(); ob3->fun(); cout << ob3 << endl; ob4 = A :: get_obj(); ob4->fun(); cout << ob4 << endl; ob5 = A :: get_obj(); ob5->fun(); cout << ob5 << endl; return 0; }
Output
Created new function 0x3721c8 Same function 0x3721c8 Same function 0x3721c8 Same function 0x3721c8 Same function 0x3721c8