Today I faced one question in interview. Is it possible to apply inheritance concept on Singleton Classes? I said since the constructor is private, we cannot extend that Singlet
Below is one implementation of singleton pattern explained in GOF about creating singleton with inheritance. Here the parent class should be modified to add a new derived class. Environment variable can be used to instantiate appropriate derived class constructor.
Mainfile – 1
#include
#include
#include "Singleton.h"
using namespace std;
int main(){
Singleton::instant().print();
cin.get();
}
Singleton.h
#pragma once
#include
using std::cout;
class Singleton{
public:
static Singleton & instant();
virtual void print(){cout<<"Singleton";}
protected:
Singleton(){};
private:
static Singleton * instance_;
Singleton(const Singleton & );
void operator=(const Singleton & );
};
Singleton.cpp
#include "Singleton.h"
#include "Dotted.h"
Singleton * Singleton::instance_ = 0;
Singleton & Singleton::instant(){
if (!instance_)
{
char * style = getenv("STYLE");
if (style){
if (strcmp(style,"dotted")==0)
{
instance_ = new Dotted();
return *instance_;
} else{
instance_ = new Singleton();
return *instance_;
}
}
else{
instance_ = new Singleton();
return *instance_;
}
}
return *instance_;
}
Dotted.h
#pragma once
class Dotted;
class Dotted:public Singleton{
public:
friend class Singleton;
void print(){cout<<"Dotted";}
private:
Dotted(){};
};