Intent:
- Define an interface for creating an object, but let subclasses decide which class to instantiate.
- Factory method lets class defer instantiation to sub classes.
- Factory method is also called virtual constructor.
- The Factory Method works by creating a parallel inheritance hierarchy to the primary inheritance hierarchy.
- The parallel set of classes are responsible for polymorphically creating an object of the primary set of classes.
- The parallel set of classes are typically called Factory classes, since they produce objects of the primary classes.
//Create the abstract 'Product' class
class Page
{
public:
virtual std::string GetPageName(void) = 0;
};
//'ConcreteProduct'#1 class
class SkillsPage : public Page
{
public:
string GetPageName(void)
{ return "SkillsPage"; }
};
//Create the abstract 'Creator' class
class Document
{
public:
//constructor
Document()
{
//CreatePages(); - Cannot be called directly in constructor because its virtual
//Should be called in the Derived class
}
void AddPages(Page* page)
{ pages_.push_back(page); }
//Factory Method
virtual void CreatePages(void) = 0;
private:
list<Page*> pages_;
};
//Create the 'ConcreteCreator' # 1 class
class Resume : public Document
{
public:
Resume() { CreatePages(); }
void CreatePages(void)
{ AddPages(new SkillsPage());
AddPages(new EducationPage());
AddPages(new ExperiencePage());
}
};
int main(int argc, char* argv[])
{
Document* doc1 = new Resume();
return 0;
}
Implementation:
Can have one of the several implementations depending on the type of problem.
1] Make the creator as an abstract class and do not provide an implementation for the factory method it declares.
2] Make the creator as a concrete class and provide a default implementation for the factory method.
3] Use parameterised factory method to create multiple kinds of products.
Consequences:
Factory methods eliminate the need to couple different classes into your code, hence promote loose coupling.
Instantiation can be controlled.
When to use it:
Class can’t anticipate the class of objects it must create.
Only creating instance is not sufficient. The object has to be initialised with some data not available to the client.