On www.dofactory.com I found a real world example of the Factory Pattern. But the code generates a warning in ReSharper about a virtual member call in the constructor.
The code causing the warning is the following:
abstract class Document
{
private List<Page> _pages = new List<Page>();
// Constructor calls abstract Factory method
public Document()
{
this.CreatePages(); // <= this line is causing the warning
}
public List<Page> Pages
{
get { return _pages; }
}
// Factory Method
public abstract void CreatePages();
}
class Resume : Document
{
// Factory Method implementation
public override void CreatePages()
{
Pages.Add(new SkillsPage());
Pages.Add(new EducationPage());
Pages.Add(new ExperiencePage());
}
}
In the consuming code, you can then simply use:
Document document = new Resume();
I do understand why it's a bad idea to call a virtual member in the constructor (as explained here).
My question is how you can refactor this in order to still use the factory pattern, but without the virtual member call in the constructor.
If I'd just remove the call to CreatePages
from the constructor, the consumer would have to explicitly call the CreatePages
method:
Document document = new Resume();
document.CreatePages();
I much more prefer the situation where creating a new Resume
is all that's needed to actually create a Resume containing pages.