2. What does a factory mean ?
• It is something which creates/manufactures
some products.
• Same is the job of factory design pattern. It is
responsible for instantiation/creation of
objects.
3. Factory Design Pattern
• Factory methods decide logically what
constructor to call.
• Instead of directly calling the constructor for a
class, we call a factory method to get the object.
• There can be multiple derived classes from a base
class. The factory method instantiates the
appropriate sub-class based on the arguments
passed to it and returns the base class type.
6. • /*Factory Class*/
• class MusicFactory
• {
• public:
• /*Factory Method*/
• Music *getMusic(genre_e genre)
• {
• Music *music = NULL;
•
• /*Logic based on Genre*/
• switch(genre)
• {
• case ROCK:
• music = new Rock();
• break;
• case POP:
• music = new Pop();
• break;
• case REGGAE:
• music = new Reggae();
• break;
• default:
• music = NULL;
• break;
• }
• return music;
• }
• };
7. Code Sample
• int main()
• {
• /*Create factory*/
• MusicFactory *musicFactory = new MusicFactory();
•
• /*Factory instantiating an object of type ROCK*/
• Music *music = musicFactory->getMusic(ROCK);
•
• cout<<"Song: ";
• if(music)
• music->song();
• else
• cout<<"Wrong selection dude/dudette !!";
• }
Editor's Notes
Call to constructor indeed creates the object and that's exactly what a factory method does but with an additional feature of option of choosing between different constructors based on some logic.
This base class object can be used to access the derived class members/methods.