jeudi 29 septembre 2016

What is the correct approach towards Factory Pattern?

I have been reading a lot of stuff regarding Factory Pattern approach and in all of them there seems to be a static method in the factory which based on switch-case returns the desired product at run-time, but this seems to violate Open Close principle as every time there is a new product the factory class needs to be modified to make necessary changes.

Below is a code i think also is in line with factory pattern but i am not sure if this approach is correct. basically what i think is that the client will know what type of factory it needs, based on that it case get the product that factory alone handles,

Please let me know if this is the right approach, or if there is a better one.

#include "iostream"
#include "memory"
using namespace std;

class AbstractDog{
    public:
        virtual void bark(void) = 0;
        AbstractDog(){cout << "AbstractDog created"<<'\n';}
        virtual ~AbstractDog(){cout << "AbstractDog destroyed"<<'\n';}
};

class chiwawa : public AbstractDog{
    public:
        void bark(void){
            cout << "bark like chiwawa"<<'\n';
        }
        chiwawa(){cout << "chiwawa created"<<'\n';}
        virtual ~chiwawa(){cout << "chiwawa destroyed"<<'\n';}
};

class alsatian : public AbstractDog{
    public:
        void bark(void){
            cout << "bark like alsatian"<<'\n';
        }
        alsatian(){cout << "alsatian created"<<'\n';}
        virtual ~alsatian(){cout << "alsatian destroyed"<<'\n';}
};


class AbstractDogFactory{
    public:
        virtual AbstractDog* getDog(void) = 0;
        AbstractDogFactory(){cout << "AbstractDogFactory created"<<'\n';}
        virtual ~AbstractDogFactory(){cout << "AbstractDogFactory destroyed"<<'\n';}
};

class smallDogFactory : public AbstractDogFactory{
    public:
        virtual AbstractDog* getDog(void){
            return new chiwawa;
        }
        smallDogFactory(){cout << "smallDogFactory created"<<'\n';}
        virtual ~smallDogFactory(){cout << "smallDogFactory destroyed"<<'\n';}
};

class bigDogFactory : public AbstractDogFactory{
    public:
        virtual AbstractDog* getDog(void){
            return new alsatian;
        }
        bigDogFactory(){cout << "bigDogFactory created"<<'\n';}
        virtual ~bigDogFactory(){cout << "bigDogFactory destroyed"<<'\n';}
};


int main() {
    auto_ptr<AbstractDogFactory> m_ptr_fact(new bigDogFactory);
    auto_ptr<AbstractDog>        m_ptr_dog(m_ptr_fact->getDog());
    m_ptr_dog->bark();
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire