Is it possible to apply inheritance to a Singleton class?

前端 未结 8 1979
孤独总比滥情好
孤独总比滥情好 2021-01-30 23:05

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

8条回答
  •  不思量自难忘°
    2021-01-30 23:43

    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(){};
    
    };
    

提交回复
热议问题