Can someone please confirm if below example has properly implemented Factory Method design pattern? If not then please suggest necessary modifications.
#include<iostream>
using namespace std;
class Stooge
{
public:
virtual void slap_stick() = 0;
};
class Larry: public Stooge
{
public:
void slap_stick()
{
cout << "Larry: poke eyes\n";
}
};
class Moe: public Stooge
{
public:
void slap_stick()
{
cout << "Moe: slap head\n";
}
};
class Curly: public Stooge
{
public:
void slap_stick()
{
cout << "Curly: suffer abuse\n";
}
};
class stoogeFactory
{
public:
static Stooge * make_stooge(int choice);
};
Stooge * stoogeFactory :: make_stooge(int choice)
{
switch (choice)
{
case 1:
return new Larry;
case 2:
return new Moe;
case 3:
return new Curly;
default:
cout<<"Invalid choice. Please try again."<<endl;
return NULL;
}
}
int main()
{
Stooge * myStooge;
int choice;
while (true)
{
cout << "Larry(1) Moe(2) Curly(3) Exit(0): ";
cin >> choice;
if (choice == 0)
break;
myStooge=stoogeFactory::make_stooge(choice);
if(myStooge!=NULL)
{
myStooge->slap_stick();
delete myStooge;
myStooge=NULL;
}
}
return 0;
}
In above code, I have created an abstract class called Stooge and 3 concrete classes Larry, Moe & Curly. The stoogeFactory class has a static function called make_stooge to accept the user choice and creates the required stooge.
This example make sure that the client should not necessarily know the all the concrete stooge classes available. Addition of new stooge class is also flexible. It also moves the lot of scattered new keyword out of client code.
Please suggest.
Thank You.
Please note the main concern i have is does this example correctly implement Factory Method. I see in GOF that Factory Method structure has four component namely abstract product class, concrete product class, abstract creator class and concrete creator class. Also, Creating objects of concrete product class is the responsibility of concrete creator class and not abstract creator class.
In my above example, i do not have concrete creator class as i don't find it necessary to have. Hence i need to know is this example correct?
Please suggest. Thanks.

stoogeFactory::make_stooge(int severity). – Mark Garcia Jan 30 at 7:21