mercredi 2 septembre 2015

Factory pattern with private constructors in C++

I am trying to implement a factory pattern that consists of

  • a factory class
  • an abstract class with protected constructor
  • inherited classes with private constructors and virtual public destructors.

I want to make sure that

  • No other one than the factory can not create any instance
  • If a new inherited class is defined it will not require any modification on interface class and already defined inherited classes. Juts new class implementation and adding into factory classes create method.

I also do not want to write same-like code(like static factory method per inited) for every inherited class and leave the future developers much work for factory connections.

i.e with pseduo code

class Factory;

class Interface
{
    protected:
        Interface(){/*Do something*/};
    public:
        virtual ~Interface(){/*Do something*/}
    /*I wish I could do below and it is valid for all inherited 
    classes but friendship is not inherited in C++*/
    //friend Interface* Factory::create(Type)
};

class InheritedA:public Interface
{
    private:
        InheritedA(){/*Do something*/};
    public:
        virtual ~InheritedA(){/*Do something*/}
    /*I dont want to do below two lines for every inherited class*/
    //friend Interface Factory::create(Type)
    //public: Interface* factoryInheritedA(){return new InheritedA();}
};

class InheritedB:public Interface
{
    private:
        InheritedB(){/*Do something*/};
    public:
        virtual ~InheritedA(){/*Do something*/}
};

class Factory
{
     static Interface* create(Interface type)       
     {
           switch(type)
           {
           case A:
                return new InheritedA();
           case B:
                return new InheritedB();
           default:
                //exceptions etc
           }
     }
}

int main()
{
    Interface* I = Factory::create(A/*or B*/);
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire