Quantcast
Channel: Applied Electronics Journal
Viewing all articles
Browse latest Browse all 21

C++ Singleton Example

$
0
0

Download here.  singleton-design-pattern

Purpose of a singleton:
To have a class which has only one instance(object)
All the objects of this class refer to same global object
that is created only once
This design pattern provides a mechanism for providing
namespaces to global variables

C++ example for singleton design pattern

// Filename  : singleton.cpp
// Author    : A.G.Raja
// License   : GPL
// Website   : http://agraja.wordpress.com

#include <iostream>

using namespace std;

class Singleton {
// constructor that is called only once
Singleton();
// object that is created only once
static Singleton *single;
public:
// method to get object
Singleton* get_instance();
// data to check the functionality
int data;
};

Singleton* Singleton::single = NULL;

Singleton* Singleton::get_instance() {
// call the constructor for the first time
// if the object has been created already
// return reference to the object already created
if(single==NULL) single = new Singleton();
return single;
}

Singleton::Singleton() {
data = 14;
}

int main() {
Singleton *s, *t ;
s = s->get_instance();
cout<<”initial value of s->data  = “<<s->data<<endl;
s->data = 25;
cout<<”modified value of s->data = “<<s->data<<endl;
t = t->get_instance();
cout<<”value of t->data          = “<<t->data<<endl;
}
// end of file singleton.cpp

Result:
initial value of s->data  = 14
modified value of s->data = 25
value of t->data          = 25

Download here.  singleton-design-pattern


Posted in Cpp Tagged: C, class, design, global, instance, object, pattern, singleton

Viewing all articles
Browse latest Browse all 21

Trending Articles