[C++] Demande précision sur Pattern Factory
Bonsoir,
Je n'arrive pas à comprendre l'intérêt du pattern Factory par rapport au polymorphisme.
Voilà deux codes qui font la même chose :
1ère version
main.cpp
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| #include <iostream>
#include "factory.h"
using namespace std;
int main()
{
Fabrique* factory = new Fabrique();
if (factory)
{
Form* f1 = factory->create("cercle");
Form* f2 = factory->create("carree");
f1->Dessiner();
f2->Dessiner();
delete f1, f2, factory;
}
return 0;
} |
factory.h
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
#ifndef FACTORY_H_INCLUDED
#define FACTORY_H_INCLUDED
#include "form.h"
class Fabrique
{
public:
Form* create(std::string quoi)
{
if (quoi == "cercle") return new Cercle();
if (quoi == "carree") return new Carree();
return NULL;
}
};
#endif // FACTORY_H_INCLUDED |
form.h
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
|
#ifndef FORM_H_INCLUDED
#define FORM_H_INCLUDED
class Form
{
public:
virtual void Dessiner() = 0;
};
class Cercle
: public Form
{
public:
Cercle(){};
~Cercle(){};
inline virtual void Dessiner()
{
std::cout << "Je suis un cercle" << std::endl;
}
};
class Carree
: public Form
{
public:
Carree(){};
~Carree(){};
inline virtual void Dessiner()
{
std::cout << "Je suis un carree" << std::endl;
}
};
#endif // FORM_H_INCLUDED |
2eme version :
main.cpp
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
#include <iostream>
#include "form.h"
using namespace std;
int main()
{
Form* f1 = new Cercle;
f1->Dessiner();
Form* f2 = new Carree;
f2->Dessiner();
delete f1, f2;
return 0;
} |
form.h
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
|
#ifndef FORM_H_INCLUDED
#define FORM_H_INCLUDED
class Form
{
public:
virtual void Dessiner() = 0;
};
class Cercle
: public Form
{
public:
Cercle(){};
~Cercle(){};
inline virtual void Dessiner()
{
std::cout << "Je suis un cercle" << std::endl;
}
};
class Carree
: public Form
{
public:
Carree(){};
~Carree(){};
inline virtual void Dessiner()
{
std::cout << "Je suis un carree" << std::endl;
}
};
#endif // FORM_H_INCLUDED |
Pour moi, la 2eme version est plus facile d'utilisation pour un résultat identique.
A mon avis, j'ai mal compris l'idée du pattern Factory :
http://come-david.developpez.com/tut...e=Fabrique#LIV
Pourtant, je pense l'avoir bien implémenté...
Pouvez vous m'éclairez d'avantage ?
Merci à tous :)