- Do we have too many classes to instantiate / or is the object creation a cumbersome process.
- Mainly we don't create the objects of a class directly but clone the existing object and change the state of the object as needed.
- The main application of such pattern is when the object creation is costly. As an example we have a database class the constructor sets up the database for the class. Now for each new user logging to the system once the system is up we don't setup the database but just clone the first object and change the user specific details like user name / password to validate the user.
A Prototype is an object which is cloneable, i.e. you can create a copy, even though you don't know what you are creating a copy of.
#include <iostream>
#include<vector>
using namespace std;
class Stooge {
public:
virtual Stooge* clone() = 0;
virtual void slap_stick() = 0;
virtual ~Stooge()
{
}
};
class Factory {
public:
static Stooge* make_stooge( int choice );
static void Cleanup();
private:
static Stooge* s_prototypes[4];
};
class Larry : public Stooge {
public:
Larry()
{
cout << "VIRAJ C" << std::endl;
}
~Larry()
{
cout<< "VIRAJ D" << std::endl;
}
Stooge* clone() { return new Larry; }
void slap_stick() {
cout << "Larry: poke eyes\n"; }
};
class Moe : public Stooge {
public:
Stooge* clone() { return new Moe; }
void slap_stick() {
cout << "Moe: slap head\n"; }
};
class Curly : public Stooge {
public:
Stooge* clone() { return new Curly; }
void slap_stick() {
cout << "Curly: suffer abuse\n"; }
};
Stooge* Factory::s_prototypes[] = {
0, new Larry, new Moe, new Curly
};
Stooge* Factory::make_stooge( int choice ) {
return s_prototypes[choice]->clone();
}
void Factory::Cleanup()
{
for(int i=1; i < 4; i++)
delete s_prototypes[i];
}
int main() {
std::vector<Stooge*> 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];
Factory::Cleanup();
}