I am learning Prototype design pattern and get confused from an example represented on this article by sourcemaking.
class Stooge
{
public:
virtual void slap_stick() = 0;
virtual Stooge* clone() = 0;
};
class Larry : public Stooge
{
public:
void slap_stick()
{
cout << "Larry: poke eyes\n";
}
Stooge* clone() { return new Larry; }
};
class Moe : public Stooge
{
public:
void slap_stick()
{
cout << "Moe: slap head\n";
}
Stooge* clone() { return new Moe; }
};
class Curly : public Stooge
{
public:
void slap_stick()
{
cout << "Curly: suffer abuse\n";
}
Stooge* clone() { return new Curly; }
};
class Factory
{
public:
static Stooge* make_stooge( int choice );
private:
static Stooge* s_prototypes[4];
};
Stooge* Factory::s_prototypes[] = {0, new Larry, new Moe, new Curly};
Stooge* Factory::make_stooge( int choice )
{
return s_prototypes[choice]->clone();
}
int main()
{
vector roles;
int choice;
while (true)
{
cout << "Larry(1) Moe(2) Curly(3) Go(0): ";
cin >> choice;
if (choice == 0)
break;
roles.push_back(Factory::make_stooge( choice ) );
}
for (int i=0; i < roles.size(); ++i)
roles[i]->slap_stick();
for (int i=0; i < roles.size(); ++i)
delete roles[i];
}
According to description Prototype Design Pattern
- Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype.
According to this. The prototype design pattern is a design pattern that is used to instantiate a class by copying, or cloning, the properties of an existing object.
As far as I know, the normal way of copying a class is to use copy constructors, overload operator=, or implement clone function to instantiate a new object by copying all of the properties of an existing object.
On the example above, I do not see how it achieves creating new objects by copying the prototype, as nor copy constructors, neither overload operator=, or appropriate clone function defined.
So can I assume that this is not an implementation of prototype design pattern? Or maybe I am wrong on my assumptions and do not understand this example?
Aucun commentaire:
Enregistrer un commentaire